NInject链式条件依赖

时间:2013-07-04 23:22:15

标签: dependency-injection ninject conditional

我对Ninject相对较新,我正试图找出一组相对复杂的依赖项。

基本上我得到的是以下依赖链:

class A {
    public A(IB b, IC c) { }
}

class B : IB {
    public B(IC c) { }
}

class C : IC { }

class SimulatedC : IC { }

class SimulatedA : A {
    public SimulatedA(IB b, IC c) : base(b, c) { }
}

模块按如下方式初始化绑定:

  • 注入A时将IC绑定到C
  • 注入SimulatedA时将IC绑定到SimulatedC

现在,这是问题所在。因为ASimulatedA都注入了B,并且因为B注入了IC,所以我无法弄清楚如何设置依赖关系链来获取注入IC的正确B实现。

这是我尝试过的:

this.Bind<IC>().To<C>().WhenInjectedInto<A>();
this.Bind<IC>().To<SimulatedC>()
    .WhenInjectedInto<SimulatedA>();

但结果是此处未描述与B的绑定,并且从B实例化的SimulatedA会被注入C而不是SimulatedC

我试过这样做:

this.Bind<IC>().To<C>().InCallScope();
this.Bind<IC>().To<SimulatedC>().InCallScope();

但是NInject只是嘲笑我。 (多个绑定例外。)

任何帮助?

谢谢!

更新:我想出了一种方法:

this.Bind<IC>().To<C>().WhenNoAncestorMatches(ShouldBeSimulated);
this.Bind<IC>().To<SimulatedC>()
     .WhenAnyAncestorMatches(ShouldBeSimulated);


private static bool ShouldBeSimulated(IContext context)
{
    var request = context.Request.ParentRequest;
    while (request != null)
    {
        if (request.Service == typeof (SimulatedA))
        {
              return true;
        }
        request = request.ParentRequest;
    }

    return false;
}

这是最好的方法吗?

0 个答案:

没有答案
相关问题