2010-12-08 106 views
2
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); 
    } 
+0

http://stackoverflow.com/questions/1377608/depedency-injection-injecting-partially-initialized-objects的副本 – onof 2010-12-09 09:36:11

回答

1

不,現在還沒有。在設置所有屬性之前,該對象不被視爲「構造」,因此它不會存儲在生命期管理器中,直到發生此情況。在這種情況下會導致堆棧溢出。