我正在處理拆分多個程序集的應用程序。每個程序集都爲外界提供接口,實例通過基於Ninject的工廠生成。Ninject注入鏈隔離
好啊,讓代碼。這是來自正在執行的程序集。
public class IsolationTestModule : NinjectModule
{
public override void Load()
{
ServiceFactory sf = new ServiceFactory();
Bind<IService>().ToMethod(context=>sf.CreatService()).InSingletonScope();
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IKernel kernel = new StandardKernel(new IsolationTestModule());
IService service = kernel.Get<IService>();
}
}
的ServiceFactory
也依賴於Ninject
,但有自己的Kernel
和自己的Module
:
public interface IService
{
void Idle();
}
public interface IDependantService
{
void IdleGracefully();
}
public class ServiceImpl : IService
{
[Inject]
public IDependantService DependantService { get; set; }
public void Idle()
{
DependantService.IdleGracefully();
}
}
public class DependantServiceImpl : IDependantService
{
public void IdleGracefully() { }
}
public class ServiceFactory
{
private IKernel _kernel = new StandardKernel(new SuppliesModule());
public IService CreatService()
{
return _kernel.Get<IService>();
}
}
public class SuppliesModule : NinjectModule
{
public override void Load()
{
Bind<IService>().To<ServiceImpl>().InSingletonScope();
Bind<IDependantService>().To<DependantServiceImpl>().InSingletonScope();
}
}
實際發生的:一切正常,直到ServiceFactory
已完成建造ServiceImpl
-instance 。在接下來的步驟中,應用程序的kernel
試圖通過IsolationTestModule
解決ServiceImpl
依賴和 - 當然 - 失敗的異常(不綁定可用,類型IDependantService
不自綁定)。在我的理解工廠的內核應該這樣做... 其實我從來不知道Ninject是那種渴望解決依賴關係,即使在那些沒有立即創建的情況下,這肯定會爲我開啓新的視野; )
要暫時解決這個問題,我改變ServiceImpl
來構造基於注射爲下圖所示:
public class ServiceImpl : IService
{
public IDependantService DependantService { get; set; }
[Inject]
public ServiceImpl(IDependantService dependantService)
{
DependantService = dependantService;
}
public void Idle()
{
DependantService.IdleGracefully();
}
}
不過,我寧願一個解決方案,不強迫我改變我的注入策略。有沒有人有一個想法,我可以如何分開注射鏈?
任何人都可以幫忙嗎? –