我在建一个主细节表格。主视图模型构造细节视图模型的实例。这些细节视图模型有几个依赖项,需要满足新的类实例。(这是因为它们需要在与主vm独立的数据上下文中操作的服务层。)
实现这些依赖关系的最佳方法是什么?
谢谢,
本
发布于 2010-08-26 12:46:00
一些可能性:
硬编码引用
下面的方法可以解决这个问题。然而,由于它引入了硬编码的依赖项,使用它是不可能的。
// 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>());工厂Func<>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-07-29 18:07:49
BookLibrary示例应用程序展示了如何使用M实现主/详细场景。它使用MEF作为IoC容器来满足ViewModel依赖关系。
发布于 2010-07-28 00:07:49
还可以使用容器构造详细视图:
var detailViewModel = container.CreateInstance<DetailViewModel>();容器将解析IAccountService和ITransactionService的依赖关系。但是,您仍将依赖IOC框架(除非使用CommonServiceLocator)。
下面是我如何使用CommonServiceLocator实现的:
this.accountService = ServiceLocator.Current.GetInstance<IAccountService>();
this.transactionService = ServiceLocator.Current.GetInstancey<ITransactionService>();https://stackoverflow.com/questions/3347818
复制相似问题