简体   繁体   English

是内核单例,是否可以在需要时创建它

[英]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. 我正在尝试首次使用Ninject,但不确定如何使用它。 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? 当使用new StandardKernel()时,我是在创建新的内核,还是仅仅是包装器类?

When you are calling new StandardKernel() it always creates a new instance of StandardKernel . 当您调用new StandardKernel()它将始终创建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. 如果您想使用Ninject作为服务定位器( 不管我不建议这样做多少 ),您必须将该实例传递给相关代码。 Or simply expose it as some public static property and init in eg on app startup. 或者简单地将其公开为一些public static属性,并在例如应用程序启动时进行初始化。

With Microsoft.Practices.ServiceLocation.ServiceLocator you can also use it this way: 通过Microsoft.Practices.ServiceLocation.ServiceLocator您还可以通过以下方式使用它:

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: 或者,在ASP Web应用程序中,您可以像这样进行访问:

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. Ninject不能以这种方式使用。 You should better try DI with constructor injection. 您最好尝试使用构造函数注入进行DI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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