我們的新項目始於使用ViewModelLocator與ViewModel結合視圖的View第一個模式。從視圖優先改變爲視圖模型優先 - 我如何處理構造函數依賴注入
我想更改爲ViewModel的第一個模式。
這裏是我的視圖模型構造:
public DeviceSelectionViewModel(IDataModel dataModel, IMessenger messenger)
{
if (dataModel == null) throw new ArgumentNullException("dataModel");
if (messenger == null) throw new ArgumentNullException("messenger");
Selector = new PlantDataTemplateSelector();
PlantSelector = new PlantNodesSelector();
Plants = new List<Plant>(0);
messenger = messenger;
messenger.Register<PlantDataLoadedMessage>(this, m => DispatcherHelper.CheckBeginInvokeOnUI(() => OnPlantDataLoaded(m.Plants)));
RefreshData(_dataModel);
}
下面是我現在首先用視圖模型選擇適當的視圖模型。
public class MainViewModel : Module
{
public MainViewModel()
{
SelectedView = new DeviceSelectionViewModel();
}
public ViewModelBase SelectedView { get; set; }
}
隨着視圖第一,我從來沒有直接通過代碼直接調用ViewModel,所以構造函數依賴注入工作正常。
現在我通過控制器ViewModel調用ViewModel,它需要ViewModel構造函數的2個參數。
在這裏適當的玩法是在控制器視圖模型中保存引用並將它們傳遞給構造函數?在這種情況下,我錯過了一些關於DI如何工作的內容?
我仍與DI(Ninject)和MVVM把拼在一起,所以要那種:)
我得到的第一個選擇,但我無法繞過第二個選擇。你能好好談談那一點嗎? – faldeland
@faldeland我更新了我的答案 –
此信息非常有幫助。我希望儘可能遵循最佳做法。我正在尋找一種可靠的方式來通過MainViewModel進行導航。我相信我會像你一樣深入到底。我希望我能找到一個有這些實踐的開源項目。 – faldeland