1

我是第一次尝试使用 Ninject,但我不知道如何使用它。假设我没有使用注入(构造函数或方法),我可以自由地做吗?

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

还是有访问内核的特定方式?new StandardKernel()我什么时候创建一个新内核,或者它只是一个包装类?

4

1 回答 1

1

当您调用new StandardKernel()它时,它总是会创建一个新的StandardKernel. 如果它是一个单例,构造函数将不会被暴露。

如果您想使用 Ninject 作为服务定位器(不管我不建议这样做多少),您必须将该实例传递给相关代码。或者只是将其公开为一些public static属性并在应用程序启动时进行初始化。

Microsoft.Practices.ServiceLocation.ServiceLocator你也可以这样使用它:

登记

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

用法

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

或者在 ASP Web 应用程序中,您可以像这样访问它:

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

但正如我所说。通常不推荐这些方法。Ninject 不打算以这种方式使用。您最好尝试使用构造函数注入进行 DI。

于 2013-02-21T23:31:35.180 回答