满足儿童视图模型依赖性

时间:2010-07-27 20:46:10

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

我正在构建一个主要细节表单。主视图模型构造详细信息视图模型的实例。这些详细信息视图模型具有几个依赖关系,需要满足 new 类实例。 (这是因为它们需要在与主vm不同的数据上下文中运行的服务层。)

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

谢谢你,

3 个答案:

答案 0 :(得分:1)

WPF Application Framework (WAF) BookLibrary 示例应用程序演示了如何使用M-V-VM实现主/明细方案。它使用MEF作为IoC容器来满足ViewModel依赖性。

答案 1 :(得分:0)

您还可以使用容器构建详细信息视图:

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

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

以下是我使用CommonServiceLocator进行的操作:

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

答案 2 :(得分:0)

一些可能性:

硬编码参考

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

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

通过IoC Framework解决

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

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

Factory Func&lt;&gt; 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());
    }
    // ....