我完成了Karl Shiffet的'InTheBox' WPF Training,發現它是學習WPF的極好資源。它提出的一件事是使用依賴注入和Unity容器。下面是提出的一些問題,我的代碼段:爲什麼要使用依賴注入容器?
public partial class App : Application {
protected override void OnStartup(StartupEventArgs e) {
IUnityContainer container = new UnityContainer();
container.RegisterType<IDialogService, ModalDialogService>(
new ContainerControlledLifetimeManager());
container.RegisterType<IEventRepository, EventRepository>(
new ContainerControlledLifetimeManager());
MainWindow window = container.Resolve<MainWindow>();
window.DataContext = container.Resolve<MainWindowViewModel>();
window.Show();
}
}
的依賴正在註冊到UnityContainer然後由UnityContainer注入MainWindowViewModel。我的問題是爲什麼使用容器?爲什麼不直接使用下面的一段代碼,就依賴注入而言達到了同樣的事情:
protected override void OnStartup(StartupEventArgs e)
{
IDialogService dialogService = new ModalDialogService();
IEventRepository eventRepository = new EventRepository();
MainWindow window = new MainWindow();
window.DataContext =
new MainWindowViewModel(eventRepository, dialogService);
window.Show();
}
我仍然注入的依賴項由該組合物根的構造,所以我看到在這種情況下沒有任何好處使用UnityContainer。
我很欣賞它明顯存在的原因,但有人可以解釋在這種情況下是否增加了什麼?另外,還有另外一種情況,像這樣使用容器真的是一件容易的事情嗎?
感謝您的額外示例,展示了在引入新的依賴關係時容器如何不允許代碼更改。 –