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开发者_StackOverflow社区 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);
}
No, not at this time. The object isn't considered "constructed" until all the properties are set, so it's not stored in the lifetime manager until after that happens. Which results in the stack overflow in this case.
精彩评论