我正在开发一个拆分为多个程序集的应用程序。每个程序集都为外部世界提供接口,实例是通过基于 Ninject 的工厂生成的。
啊,好吧,让 Code。这是来自正在执行的大会。
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
尝试通过解决ServiceImpl
依赖关系IsolationTestModule
- 当然 - 失败并出现异常(没有可用的绑定,类型IDependantService
不可自绑定)。据我了解,factory的内核应该这样做......实际上我从来不知道 Ninject 会急于解决依赖关系,即使在它没有立即创建的那些情况下,这肯定会为我打开新的视野;-)
为了暂时解决这个问题,我将注入更改ServiceImpl
为基于构造函数的注入,如下所示:
public class ServiceImpl : IService
{
public IDependantService DependantService { get; set; }
[Inject]
public ServiceImpl(IDependantService dependantService)
{
DependantService = dependantService;
}
public void Idle()
{
DependantService.IdleGracefully();
}
}
不过,我更喜欢不会强迫我改变注射策略的解决方案。有谁知道我如何分离注入链?