【问题标题】:How/Where to instantiate model objects in MVVM using PRISM and Unity如何/在何处使用 PRISM 和 Unity 在 MVVM 中实例化模型对象
【发布时间】:2014-11-21 03:37:09
【问题描述】:

我尝试使用 PRISM 和 UNITY 实现我的第一个应用程序。 所以我尝试将我的应用程序拆分为几个模块。

在我的模块中,我有相关的视图以及视图模型。

目前我实例化我的视图模型并在后面的视图代码中设置我的视图的数据上下文:

public partial class View : UserControl
{
    public View(IViewModel vm)
    {
        InitializeComponent();
        this.DataContext = vm;
    }
}

我的模型是使用我的视图模型 ctor 中的统一容器实例化的。

public ViewModel(IEventAggregator eventAggregator, IUnityContainer container)
{
    _eventAggregator = eventAggregator;

    _model = container.Resolve<Model>();
    this._model.PropertyChanged += new PropertyChangedEventHandler(OnModelPropertyChanged);
}

在使用统一容器之前,我通过 ViewModels 构造函数通过依赖注入来注入模型。

但这似乎不起作用。我尝试了以下方式:

public ViewModel(IEventAggregator eventAggregator, Model model)
{
    _eventAggregator = eventAggregator;
    _model = model
    this._model.PropertyChanged += new PropertyChangedEventHandler(OnModelPropertyChanged);
}

这个实现给了我一个例外,我也不知道如何设置容器,以便模型注入按照我尝试的方式工作。

我想做的是在模块类中实例化我的模型。从那里我想将它注入我的视图模型。

所以我的问题是:

  1. 我目前的做法是否正确?
  2. 有没有办法在模块类中实例化模型并将它们注入到视图模型中,如果是的话,如何以及网络上有任何示例?

【问题讨论】:

    标签: c# mvvm dependency-injection unity-container prism


    【解决方案1】:

    查看 Prism 5 (http://msdn.microsoft.com/en-us/library/gg430879(v=pandp.40).aspx) 的 UI 组合快速入门。它完全符合您的要求。
    1) 在您的引导程序中注册模块:

    moduleCatalog.AddModule(typeof(EmployeeModule.ModuleInit));
    

    2) 在您的模块实现中注册您的模型类型(如果您的模型是共享的,则在引导程序中注册)

    this.container.RegisterType<IEmployeeDataService, EmployeeDataService>();
    

    3) 通过构造函数将模型注入到视图模型中

    public EmployeeListViewModel(IEmployeeDataService dataService, IEventAggregator eventAggregator) { }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多