2013-02-20 27 views
1

我想第一次使用Ninject,並且我不確定如何使用它。 可以說我不使用注射(構造函數或方法),我可以自由地做什麼;是內核單例,我可以在需要時創建它

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

或者是否有訪問內核的特定方式?當我創建一個新的內核時new StandardKernel(),還是僅僅是一個包裝類?

回答

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。

+0

這就是我想實現只用接口定義域事件的情景,我已經用事先思考這樣做。那麼,這是可能與一個構造函數(最好的方法)注入?而且,我也不想將接口綁定到具體的類,而寧願使用DI工具包來掃描我的程序集以獲得實現類。 – hazimdikenli 2013-02-22 09:12:54

相關問題