【发布时间】:2011-03-21 20:11:20
【问题描述】:
我正在构建一个主从表单。主视图模型构造详细视图模型的实例。这些细节视图模型有几个依赖项,需要 new 类实例来满足这些依赖项。 (这是因为他们需要在与主虚拟机不同的数据上下文中运行的服务层。)
实现这些依赖关系的最佳方式是什么?
谢谢你,
本
【问题讨论】:
标签: c# mvvm dependencies ioc-container master-detail
我正在构建一个主从表单。主视图模型构造详细视图模型的实例。这些细节视图模型有几个依赖项,需要 new 类实例来满足这些依赖项。 (这是因为他们需要在与主虚拟机不同的数据上下文中运行的服务层。)
实现这些依赖关系的最佳方式是什么?
谢谢你,
本
【问题讨论】:
标签: c# mvvm dependencies ioc-container master-detail
你也可以使用容器来构造详细视图:
var detailViewModel = container.CreateInstance<DetailViewModel>();
容器将解析 IAccountService 和 ITransactionService 的依赖关系。但是您仍然会依赖 IOC 框架(除非您使用 CommonServiceLocator)。
这是我使用 CommonServiceLocator 的方法:
this.accountService = ServiceLocator.Current.GetInstance<IAccountService>();
this.transactionService = ServiceLocator.Current.GetInstancey<ITransactionService>();
【讨论】:
WPF Application Framework (WAF) 的 BookLibrary 示例应用程序展示了如何使用 M-V-VM 实现 Master/Detail 场景。它使用 MEF 作为 IoC 容器来满足 ViewModel 的依赖关系。
【讨论】:
以下方法可以解决问题。但是,由于它引入了硬编码的依赖关系,所以使用它是不可能的。
// in the master view model
var detailViewModel = new DetailViewModel(new AccountService(), new TransactionService());
另一个选项是让父视图模型保存对 IoC 框架的引用。这种方法引入了对 IoC 框架的主视图模型依赖。
// in the master view model
var detailViewModel = new DetailViewModel(resolver.GetNew<IAccountService>(), resolver.GetNew<IAccountService>());
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());
}
// ....
【讨论】: