【发布时间】:2012-07-05 06:59:26
【问题描述】:
我正在开发一个拆分为多个程序集的应用程序。每个程序集都为外部世界提供接口,实例是通过基于 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-实例之前一切正常。在下一步中,应用程序的 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();
}
}
尽管如此,我更喜欢一种不会强迫我改变注射策略的解决方案。有谁知道如何分离注入链?
【问题讨论】:
标签: c# .net binding dependency-injection ninject