【问题标题】:Satisfying Child View Model Dependencies满足子视图模型依赖
【发布时间】:2011-03-21 20:11:20
【问题描述】:

我正在构建一个主从表单。主视图模型构造详细视图模型的实例。这些细节视图模型有几个依赖项,需要 new 类实例来满足这些依赖项。 (这是因为他们需要在与主虚拟机不同的数据上下文中运行的服务层。)

实现这些依赖关系的最佳方式是什么?

谢谢你,

【问题讨论】:

    标签: c# mvvm dependencies ioc-container master-detail


    【解决方案1】:

    你也可以使用容器来构造详细视图:

    var detailViewModel = container.CreateInstance<DetailViewModel>();
    

    容器将解析 IAccountService 和 ITransactionService 的依赖关系。但是您仍然会依赖 IOC 框架(除非您使用 CommonServiceLocator)。

    这是我使用 CommonServiceLocator 的方法:

    this.accountService = ServiceLocator.Current.GetInstance<IAccountService>();
    this.transactionService = ServiceLocator.Current.GetInstancey<ITransactionService>();
    

    【讨论】:

      【解决方案2】:

      WPF Application Framework (WAF)BookLibrary 示例应用程序展示了如何使用 M-V-VM 实现 Master/Detail 场景。它使用 MEF 作为 IoC 容器来满足 ViewModel 的依赖关系。

      【讨论】:

        【解决方案3】:

        一些可能性:

        硬编码引用

        以下方法可以解决问题。但是,由于它引入了硬编码的依赖关系,所以使用它是不可能的。

        // in the master view model
        var detailViewModel = new DetailViewModel(new AccountService(), new TransactionService());
        

        通过 IoC 框架解决

        另一个选项是让父视图模型保存对 IoC 框架的引用。这种方法引入了对 IoC 框架的主视图模型依赖。

        // in the master view model
        var detailViewModel = new DetailViewModel(resolver.GetNew<IAccountService>(), resolver.GetNew<IAccountService>());
        

        工厂函数s

        class MasterViewModel {
          public MasterViewModel(Func<Service.IAccountService> accountServiceFactory, Func<Service.ITransactionService> transactionServiceFactory) {
            this.accountServiceFactory = accountServiceFactory;
            this.transactionServiceFactory = transactionServiceFactory;
        
            // instances for MasterViewModel's internal use
            this.accountService = this.accountServiceFactory();
            this.transactionService = this.transactionServiceFactory():
          }
          public SelectedItem { 
            set {
               selectedItem = value;
               DetailToEdit = new DetailViewModel(selectedItem.Id, accountServiceFactory(), transactionServiceFactory());
            }
            // ....
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-20
          • 2020-09-11
          • 1970-01-01
          • 2018-10-03
          • 2023-04-02
          • 1970-01-01
          相关资源
          最近更新 更多