views:

78

answers:

4

Hello,

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 dependencies?

Thank you,
Ben

A: 

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>();
David Lynch
Thanks for this idea!
Ben Gribaudo
+1  A: 

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.

jbe
A: 

I'm trying to solve this problem myself. Here is a blog entry that is relevant: http://www.primordialcode.com/blog/post/silverlight-mvvm-ioc-part-3

Dave Hillier
A: 

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());
    }
    // ....
Ben Gribaudo