开发者

Satisfying Child View Model Dependencies

I'm building a master-detail form. The master view model constructs instances of the details view model. These details view models have several dependencies which need to be satisfied with new class instances. (This is because they need service layers that operate in a separate data context from the master vm.)

What would be the best way to fulfill these dep开发者_运维技巧endencies?

Thank you,

Ben


The BookLibrary sample application of the WPF Application Framework (WAF) shows how to implement a Master/Detail scenario with M-V-VM. It uses MEF as IoC Container to satisfy the ViewModel dependencies.


You can also use the container to construct the detail view:

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

The container will resolve the dependencies for IAccountService and ITransactionService. But you will still have a dependency on the IOC framework (unless you use the CommonServiceLocator).

Here is how I do it using the CommonServiceLocator:

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


Some Possibilities:

Hard-Coded References

The following approach would solve the problem. However, as it introduces hard-coded dependencies, using it is out of the question.

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

Resolution via IoC Framework

Another option would be for the parent view model to hold a reference to an IoC framework. This approach introduces a master view model dependency on the IoC framewok.

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

Factory 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());
    }
    // ....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜