[英]Is it ok to register the Ninject kernel in the kernel itself?
我有一個麻煩的Windows服務( 請參閱此問題 ),並且我正在考慮創建一個自定義范圍工廠,以在每次服務打勾時生成一個新的范圍。
我計划將內核注入該工廠,以便它可以在每個刻度上返回該服務的新范圍,並在每個刻度之后銷毀/釋放該范圍。
為方便起見,我計划將其添加到我的RegisterServices()方法中:
kernel.Bind<IKernel>().ToConstant(kernel);
我的自定義范圍工廠將如下所示:
public class CustomScopeFactory : ICustomScopeFactory
{
private readonly IKernel kernel;
public CustomScopeFactory(IKernel kernel)
{
this.kernel = kernel;
}
public ICustomScope CreateScope()
{
return kernel.Get<ICustomScope>();
}
public void DisposeScope(ICustomScope scope)
{
kernel.Release(scope);
}
}
我通常不會考慮在內核中注冊或注入內核,但是在這種情況下,我認為這是一個有效的用例。
那么,可以在內核本身中注冊Ninject內核嗎? 任何想法或選擇將不勝感激。
那么,可以在內核本身中注冊Ninject內核嗎?
是的,這沒有問題。 可以將內核注入類中,只要這些類位於Composition Root中即可 。 將內核注入到Composition Root之外的類中會導致Service Locator反模式 ,而將其注入到Composition根內部的類中只是機制 。
您不需要注冊IKernel
。 對於具有IKernel
依賴項(構造函數,字段或屬性)的任何容器創建的類,它都會自動注入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.