我目前正在開發一個新的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中解析所有的依賴關係,以便容器調用我? :)