是否可以在Unity中创建带循环引用的对象?

时间:2010-12-08 07:24:37

标签: unity-container circular-dependency

public interface IBaz { IBar bar { get; set; } }
public class Baz : IBaz
{
    public IBar bar { get; set;  }
    public Baz(IBar bar) { this.bar = bar;  }
}

public interface IBar { IBaz baz { get; set;  } }
public class Bar : IBar
{
    public IBaz baz { get; set; }
    public Bar(IBaz baz) { this.baz = baz; }
}

class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();

        container.RegisterType<IBar, Bar>(new ContainerControlledLifetimeManager());
        container.RegisterType<IBaz, Baz>(new ContainerControlledLifetimeManager());

        //Problem 1: I get a stack-overflow, but I am using the singleton lifetime manager?
        var bar = container.Resolve<IBar>(); 
        var baz = container.Resolve<IBaz>();

        //Problem 2: I want Unity to do this automatically for me. How?
        bar.baz = baz; baz.bar = bar;

        var result = object.ReferenceEquals(bar, baz.bar) && object.ReferenceEquals(baz, bar.baz); 
    }

1 个答案:

答案 0 :(得分:1)

不,不是在这个时候。在设置了所有属性之前,该对象不被视为“构造”,因此在此之后它才会存储在生命周期管理器中。在这种情况下,这会导致堆栈溢出。