Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Instance using Ninject

Tags:

c#

ninject

How can I get a single instance using Ninject? Here's my Service Module:

public class ServicesModule : NinjectModule
{
    public override void Load()
    {
        Kernel.Bind<IDocumentServiceApi>().To<DocumentServiceApi>().InRequestScope();
        Kernel.Bind<IConfigurationService>().To<ConfigurationService>().InRequestScope();
        Kernel.Bind<IReportGenerationProcessor>().To<ReportGenerationProcessor>().InRequestScope();
    }
}

I need an instance of IReportGenerationProcessor to fire off a message I am receiving from an Azure Service Bus Queue.

I've seen a lot of different ways, but none have worked for me. I constantly get the error :Object instance not set to an instance of an object.

//I do instantiate this class using new WebJobBase();
public class WebJobBase
    {
        public void ProcessMessage(BrokeredMessage message)
        {
                // Just need an instance of IReportGenerationProcessor here
                var _processor = new ReportGenerationProcessor();
                _processor.ProcessMessage(message);
        }
    }

Here's my IReportGenerationProcessor implementation:

    public interface IReportGenerationProcessor
    {
        DocumentMetaData ProcessMessage(BrokeredMessage message);
    }
    public class ReportGenerationProcessor : IReportGenerationProcessor
    {
        // Go figure these don't work either
        [Inject]
        public IConfigurationService _config { get; set; }
        [Inject]
        public IDocumentServiceApi _docService { get; set; }

        public DocumentMetaData ProcessMessage(BrokeredMessage message)
        {
            var report = message.GetBody<ReportMetaData>();

            //Do some stuff
            return new DocumentMetaData(); // just a place holder
        }
    }

If I can provide more information, please let me know. I'm not too knowledgeable on Ninject.

like image 604
Mark C. Avatar asked Jun 17 '26 23:06

Mark C.


1 Answers

Okay, so the documentation kind of hinted at this, but they didn't use an Interface and registered .ToSelf().

Basically I needed to instantiate a new StandardKernel with my ServicesModule from above, and call the .Get<>(); method for my registered Interface.

IKernel kernel = new StandardKernel(new ServicesModule());
var processor = kernel.Get<IReportGenerationProcessor>();
processor.ProcessMessage(message);
like image 112
Mark C. Avatar answered Jun 19 '26 12:06

Mark C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!