2011-08-31 126 views
5

我目前正在開發一個新的WPF應用程序,我將Unity用作DI容器。截至目前,我在做DI這樣在App.xaml.cs如何做好萊塢原則+ DI + WPF + Unity

protected override void OnStartup(StartupEventArgs e) 
    { 
     var container = new UnityContainer(); 
     UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); 
     container = (UnityContainer)section.Configure(container); 
     WPFUnityContainer.Instance = container; 

     var mainwindow = new MainWindow(); 
     var mainmodel = container.Resolve<ViewModel.MainWindowViewModel>(); 
     mainwindow.DataContext = mainmodel; 
     mainwindow.Show(); 

     base.OnStartup(e); 
    } 

的MainWindowViewModel的點擊率是這樣的:

public MainWindowViewModel(IUserRepository userRepository, IGroupRepository groupRepository) 
    { 
     this._ManagementWorkSpaces = new ObservableCollection<WorkspaceViewModel>(); 
     this._ManagementWorkSpaces.Add(new ManageApplicationsViewModel()); 
     this._ManagementWorkSpaces.Add(new ManageUserViewModel(userRepository, groupRepository)); 

    } 

現在讓我們來看看ManageUserViewModel:

public ManageUserViewModel(IUserRepository userRepository, IGroupRepository groupRepository) 

    {... 
     this._ManageGroupsCommand = new DelegateCommand(() => 
     { 
      LookupGroupDialogViewModel vm=new LookupGroupDialogViewModel(groupRepository); 
      View.LookupGroupDialogWindow vw=new View.LookupGroupDialogWindow(); 
      ModalDialogService.Service.ShowDialog(vw, vm, returnedVM => 
       { 
        if (returnedVM.SelectedGroup!=null) 
         this.SelectedUser.Groups.Add(returnedVM.SelectedGroup); 
       }); 
     }); 

    } 

正如你所看到的,我正在注入groupRepository來傳遞給LookUpGroupDialogViewModel。我可以將IGroupRepository從ManageUserViewModel的ctr中取出並直接通過容器解決,但我認爲這違反了好萊塢原則。我如何在WPF中解析所有的依賴關係,以便容器調用我? :)

回答

5

它看起來好像你添加到_ManagementWorkSpaces視圖模型必須有某種形式的共同抽象(除非集合是完全無類型的,並且簡單地接受任何object) - 我假設這是WorkspaceViewModel類型。

這意味着,你可以巧妙地通過改變構造看起來像這樣解決問題:

public MainWindowViewModel(ObservableCollection<WorkspaceViewModel> workSpaces) 
{ 
    this._ManagementWorkSpaces = workSpaces; 
} 

讓你Composition RootObservableCollection<WorkspaceViewModel>實例是如何解決的。