我们有 3 个不同的链接类。 我们统一注册。
我们在正确解决这些问题时遇到问题。
这些类看起来像这样:
public class A: IA
{
public IB B { get; private set; }
public IC C { get; private set; }
public A(IB b, IC c)
{
this.B = b;
this.C = c;
}
}
public class B : IB
{
public IC C { get; private set; }
public B(IC c)
{
this.C = c;
}
}
public class C :IC{}
public interface IA
{
IB B { get; }
IC C { get; }
}
public interface IB{
IC C { get; }
}
public interface IC{}
统一配置如下所示:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="IA" mapTo="A" />
<register type="IB" mapTo="B" />
<register type="IC" mapTo="C" />
</container>
</unity>
这是我们的主类,我们试图从统一中解析 A 并在 A 对象和 B 对象中获得相同的 C 对象。
public class Main
{
public Main()
{
//This works..
IC objC = new C();
IB objB =new B(objC);
IA objA = new A(objB,objC);
//We want to do this.
//How do we register in Unity to ensure we get the same object for C in both A and B
IA obj1 = Unity.Resolve<IA>();
Debug.Assert(obj1.C == obj1.B.C);
//It's very important that two diffrent resolved objects of A don't have the same C object
IA obj2 = Unity.Resolve<IA>();
Debug.Assert(obj2.C == obj2.B.C);
Debug.Assert(obj1.C != obj2.C);
}
}
这有可能实现统一吗? 也许通过使用一些终身管理?
最佳答案
您可以对 C 使用 Per Resolve 生命周期管理器。这会告诉 Unity 为每个单独的 Resolve 调用创建一个新的 C 实例。然而,在一次解析期间,仅使用一个 C 实例来注入(inject)对象图。
配置如下所示:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="IA" mapTo="A" />
<register type="IB" mapTo="B" />
<register type="IC" mapTo="C">
<lifetime type="perresolve"/>
</register>
</container>
</unity>
使用上述配置,断言将通过。
关于c# - Unity解析对象并在依赖解析对象中获取相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19787013/