我正在嘗試在WPF應用程式中實作 MVVM 模式。我已經使用依賴注入來獲取我的視圖模型的建構式中的型別,就像這樣。
private IEntity _newEntity;
private readonly IEntityService _entityService;
public MainViewModel(IEntity entity, IEntityService entityService)
{
_newEntity = entity;
_entityService = entityService;
}
現在我可以出于任何原因這樣做_newEntity = new Entity();還是反模式?也就是說能ViewModel不能加上一個具體的型別?
uj5u.com熱心網友回復:
這取決于您要歸檔的內容。
如果你想像這樣呼叫s 構造_newEntity = new Entity();函式MainViewModels
public MainViewModel(IEntityService entityService)
{
_newEntity = new Entity();
_entityService = entityService;
}
那么您正在Entity建構式中創建一個新的類物件,并且不再需要通過依賴注入作為引數傳遞給建構式。但是現在每個MainViewModel都有不同的實體,Entity而且可能更重要的是,您將無法以干凈的方式Entity從其他 ViewModel 或服務訪問它們。如果這是你想要發生的,那很好。
如果您希望其他 ViewModel 或服務使用相同的實體,您可以在您的 DI(依賴注入)容器中Entity注冊一個實體。Entity大多數 DI 容器為該用例提供功能,例如containerRegistry.RegisterSingleton<IEntity>();在Prism中。
有了Entity這個IEntity...沒原因。這遵循YAGNI(你不需要它)原則,比如不要實作你可能不需要的抽象。在這種情況下,您可以將 注冊Entity為具體型別而不是像這樣的介面containerRegistry.RegisterSingleton<Entity>();并將您的更改MainViewModel為
private Entity _newEntity;
private readonly IEntityService _entityService;
public MainViewModel(Entity entity, IEntityService entityService)
{
_newEntity = entity;
_entityService = entityService;
}
SingletonSean還提供了一個不錯的視頻,其中他不使用介面,而是使用 ViewModel 的建構式引數的具體類。
請注意,我最近才進入 WPF,因此在撰寫此答案時我并沒有聲稱自己是專家。
uj5u.com熱心網友回復:
如果視圖模型負責創建物體,那么通過做來創建這些物體new Entity()是非常好的。
另一種選擇是向視圖模型注入一個代表視圖模型創建物體的工廠。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/481282.html
