4

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

满足这些依赖关系的最佳方式是什么?

谢谢你,

4

3 回答 3

1

WPF 应用程序框架 (WAF)BookLibrary示例应用程序展示了如何使用 MV-VM 实现 Master/Detail 场景。它使用 MEF 作为 IoC 容器来满足 ViewModel 依赖项。

于 2010-07-29T18:07:49.693 回答
0

您还可以使用容器来构造详细视图:

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

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

以下是我使用 CommonServiceLocator 执行此操作的方法:

this.accountService = ServiceLocator.Current.GetInstance<IAccountService>();
this.transactionService = ServiceLocator.Current.GetInstancey<ITransactionService>();
于 2010-07-28T00:07:49.170 回答
0

一些可能性:

硬编码参考

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

// 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());
    }
    // ....
于 2010-08-26T12:46:00.927 回答