我们有 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>
这是我们的 Main 类,我们试图从 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);
}
}
这有可能实现统一吗?也许通过使用一些终身管理?