【问题标题】:Ninject injection chain isolationNinject 注入链隔离
【发布时间】: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


    【解决方案1】:

    您的观察是正确的。 Ninject 将对ToMethod 创建的对象进行属性注入。此外,您使用构造函数注入的解决方案是正确的方法。无论如何,构造函数注入是使用 Ninject 的首选方式。属性注入只能用于可选依赖项。

    您应该考虑的是只使用一个内核。在一个应用程序中使用多个内核实例是非常不寻常的。

    【讨论】:

    • 感谢您的回复,雷莫。事实上,我正在创建三个完全独立的程序集。那些——巧合的是,你可能会说——有使用 Ninject 的习惯,并且可以同时使用。每个都在内部使用 Ninject,但只向外部公开工厂类和接口。我已经切换到构造函数注入了,所以基本解决了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2017-05-28
    • 2012-11-08
    相关资源
    最近更新 更多