简体   繁体   中英

is kernel singleton, can I create it whenever needed

I am trying to use Ninject for the first time, and I am not sure how to use it. Lets say that I am not using injection (constructor or method), can I freely do;

var kernel = new StandardKernel();
var types = kernel.GetBindings(typeof(IDomainEventHandler<T>))
.GetImplementingTypes();

or is there a specific way of accessing the kernel? When new StandardKernel() am I creating a new kernel, or is it just a wrapper class?

When you are calling new StandardKernel() it always creates a new instance of StandardKernel . If it would be a singleton, the constructor would not be exposed.

If you want to use Ninject as service locator ( does not matter how much I do not recommend to do so ) you have to pass that instance to dependent code. Or simply expose it as some public static property and init in eg on app startup.

With Microsoft.Practices.ServiceLocation.ServiceLocator you can also use it this way:

Registration

IKernel kernel = new StandardKernel();
IServiceLocator ninjectServiceLocator = new NinjectServiceLocator(kernel);
Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(() => ninjectServiceLocator);

Usage

var service = ServiceLocator.Current.GetInstance<IMyService>();

Or in ASP web application you can acces it like:

var kernel = ((NinjectHttpApplication) HttpContext.ApplicationInstance).Kernel;
var service = kernel.Get<IService>();

But as I said. These approaches are not genarally recommended. Ninject is not intended to be used this way. You should better try DI with constructor injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM