假设我有以下类要使用 Ninject 构建,箭头表示依赖项。
A > B > D
A > C > D
我想将 Ninject 配置为 A 是 transient 范围的,即每次您向 Ninject 询问 A 时,您都会得到一个新的。我也希望 B 和 C 是暂时的,每次你要求 A 时你都会得到一个新的。但我希望 D 在 B 和 C 中重复使用。所以每次我要求 A 时,我都想要 Ninject构造每个对象中的一个,而不是两个 D。但我不希望 Ds 在不同的 As 中重复使用。
使用 Ninject 进行设置的最佳方法是什么?
更新:
经过更多研究,似乎 Unity 有一个 PerResolveLifetimeManager 可以满足我的需求。是否有 Ninject 等价物?
最佳答案
Ninject 支持四个内置 object scopes out of the box : transient 、单例、线程、请求。
所以没有任何 PerResolveLifetimeManager
像范围一样,但您可以通过使用 InScope
注册自定义范围来轻松实现它。方法。
事实证明,有一个现有的 Ninject 扩展: ninject.extensions.namedscope
它提供了 InCallScope
方法这就是你正在寻找的。
但是,如果您想自己做,您可以使用自定义 InScope
代表。在哪里可以使用主IRequest
类型的对象 A
将其用作范围对象:
var kernel = new StandardKernel();
kernel.Bind<A>().ToSelf().InTransientScope();
kernel.Bind<B>().ToSelf().InTransientScope();
kernel.Bind<C>().ToSelf().InTransientScope();
kernel.Bind<D>().ToSelf().InScope(
c =>
{
//use the Request for A as the scope object
var requestForA = c.Request;
while (requestForA != null && requestForA.Service != typeof (A))
{
requestForA = requestForA.ParentRequest;
}
return requestForA;
});
var a1 = kernel.Get<A>();
Assert.AreSame(a1.b.d, a1.c.d);
var a2 = kernel.Get<A>();
Assert.AreSame(a2.b.d, a2.c.d);
Assert.AreNotSame(a1.c.d, a2.c.d);
样本类在哪里:
public class A
{
public readonly B b;
public readonly C c;
public A(B b, C c) { this.b = b; this.c = c; }
}
public class B
{
public readonly D d;
public B(D d) { this.d = d; }
}
public class C
{
public readonly D d;
public C(D d) { this.d = d; }
}
public class D { }
关于inversion-of-control - Ninject 范围 - 在正在构建的整个图形中使用相同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14044202/