2010-06-05 5 views
6

나는 Unity를 꽤 오랫동안 사용 해왔다. 그러나 나는 항상 생성자 주입과 함께 사용했다. 내 명령 모델에 주입해야하는 클래스 수를 줄이기 위해 (내 명령이 의존하는대로) Property Injection을 사용하여 대형 생성자 매개 변수 목록에 대한 요구 사항을 제거하는 개념을 만들려고했습니다. 시나리오는 다음과 같습니다 ...스택 오버플로를 일으키는 Unity와의 속성 주입

어떤 방식으로 hosing View Model을 사용/업데이트하는 명령에있는 명령이있는 View Model을 생성하고 있습니다. 뷰 모델의 인스턴스를 뷰 모델 속성에있는 명령 생성자로 전달하고 싶습니다. 예 :

public MainViewModel 
{ 
    public MainViewModel() 
    { 
     Customers = new ObservableCollection<CustomerViewModel>(); 
    }   

    [Depedency("LoadCommand")] 
    public ICommand LoadCustomersCommand { get; set; } 

    public ObservableCollection<CustomerViewModel> Customers { get; private set; } 
} 

public LoadCustomersCommand : ICommand 
{ 
    public LoadCustomersCommand(MainViewModel mainViewModel) 
    { 
     //Store view model for later use 
    } 

    //... implementation 
} 

//Setup code in App.Xaml 

IUnityContainer unityContainer = new UnityContainer(); 
unityContainer.RegisterType<ICommand, LoadCommand>("LoadCommand"); 
unityContainer.RegisterType<MainViewModel>(new ContainerControlledLifetimeManager()); 

MainViewModel 클래스를 해결할 때 (Visual Studio가 돌아 오면) StackOverflow 예외가 발생합니다. 이제 Unity가 MainViewModel의 인스턴스를 생성하고 기본적으로 싱글 톤이므로 View Model의 인스턴스를보고 새롭게 생성 된 MainViewModel에서 전달하는 Command를 생성 할 것이지만 분명히 틀 렸습니다.

아이디어가 있으십니까?

답변

9

이것은 Circular References 오류입니다.이 말은 개발자의 책임입니다. 따라서 MainViewModel은 MainViewModel -> StackOverflow에 대한 LoadCustomersCommand를 참조합니다.

당신이 할 수있는 유일한은

public class MainViewModel 
{ 
    public MainViewModel() 
    { 
     Customers = new ObservableCollection<CustomerViewModel>(); 
    }   

    //no dependency. 
    public ICommand LoadCustomersCommand { get; set; } 

    public ObservableCollection<CustomerViewModel> Customers { get; private set; } 
} 

이며 대답하고 링크에 대한 다음

var mainModel = unityContainer.Resolve<MainViewModel>(); 
mainModel.LoadCustomersCommand =  unityContainer.Resolve<ICommand>("LoadCommand"); 
+0

감사를 수행해야 해결하기 위해. 나는 그것이 사실일지도 모르지만 속성 주입으로 인해 속성 클래스가 인스턴스화되고 '순환'참조가 문제가되지 않을 때 MainViewModel이 컨테이너에 있었을 것이라고 생각했지만 명백하게 아닙니다. 청소 해 주셔서 감사합니다! – Adam

관련 문제