MVVM and IOC: Handling View Model’s Class Invariants

I’m not quite sure what the issue is, so I’ll use a simple and contrived example.

Let’s say you have a CustomerListViewModel which lists a summary of each customer. When you select a customer, you want to display a CustomerDetailViewModel. This could take either a customer ID, or an ICustomer type which is populated previously in the CustomerListViewModel with the customer details (depending on when you want to load the data for example).

I think what you’re asking is what happens if CustomerDetailViewModel also takes a series of services as dependencies which you want to resolve through the container (normally for dependency chains).

As you’re doing view model first, you need to instantiate the CustomerDetailViewModel from the CustomerListViewModel, and you want to do so via the container so that the dependencies are injected appropriately.

Therefore, as you mention, you would normally do this through an abstract factory pattern, for example ICustomerDetailViewModelFactory which gets passed as a service to the CustomerListViewModel.

This factory type has a ICustomerDetailViewModel GetCustomerDetailViewModel(ICustomer customer) method. This factory type will require a reference to your IoC container.

When resolving the ICustomerDetailViewModel in your GetCustomerDetailViewModel factory method, you can specify the value you wish to use for the ICustomer constructor parameter when you call Resolve on your container.

For example, Unity has parameter overrides, and see here for Castle Windsor support. Castle Windsor also has a typed factory facility, so that you don’t need to implement the concrete factory types, just the abstractions.

So I would go with option 2! We use Caliburn.Micro, it solves a lot of MVVM problems, but I don’t know of any frameworks which address this issue.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)