我目前正在学习MVVM模式,我正在跟随的教程使用Unity进行DI。我以前没有真正使用过这种方式的DI,只是想要澄清一下我对这个特定代码如何工作的想法。
在View中,我有:
private ViewModel vm;
[Dependency]
public ViewModel VM
{
set
{
vm = value;
this.DataContext = vm;
}
}
其中的dependency属性告诉Unity在这里进行注入。ViewModel构造函数需要一个IQuoteSource对象,该对象已在Unity中注册:
IUnityContainer container = new UnityContainer();
RandomQuoteSource randomQuoteSource = new RandomQuoteSource();
container.RegisterInstance<IQuoteSource>(randomQuoteSource);
MainWindow window = container.Resolve<MainWindow>();
window.Show();
这是如何工作的呢?因为我从未使用上面的属性显式地创建ViewModel对象。如果是在Unity中处理的,那么它是如何实现的呢?
谢谢。