我非常喜歡依賴注入的想法。我在應用這個概念時遇到了麻煩,因爲我看到的大多數例子都是針對ASP.NET MVC的。在MVVM中傳遞服務
這就是我得到的:WPF - > Services - > Repository。服務獲取注入庫,並且我的視圖模型(至少有一個)會注入服務。
然後在我的WPF App.xaml中,我重寫了OnStartup方法。這就是我創建Ninject並解決我的第一個觀點的地方。
當涉及到多個視圖時,我迷了路。例如,假設我將ServiceA和ServiceB注入了我的第一個視圖模型(在App.xaml中)。比方說,我想在另一個視圖模型的構造函數中使用ServiceC,我將如何獲得注入構造函數的內容?
在代碼中說,是這樣的:
public class ViewModel1
{
private readonly IServiceA serviceA;
private readonly IServiceB serviceB;
public ViewModel1(IServiceA serviceA, IServiceB serviceB)
{
this.serviceA = serviceA;
this.serviceB = serviceB;
}
public void OpenASettingsWindow()
{
// How do I resolve this view?
var window = new View(new ViewModel2(new ServiceC()));
}
}