ViewModelLocator with IOC child containers?

939 Views Asked by At

How do you implement the ViewModelLocator pattern when you're using IOC child containers? A typical locator implementation is something like:

public IViewModel ViewModel
{
   get { return Services.ServiceLocator.GetInstance<IViewModel>(); }
}

where Services.ServiceLocator is a read only static property. But this breaks down if you're using child containers. Here's my definition for Services.ServiceLocator using child containers:

public static IServiceLocator ServiceLocator
{
    get { return RootContext.ServiceLocator; }
}

Clearly this is not correct: my injected dependencies will come from the root container instead of the child container. (The child container is created and boot strapped by something other than my current view. Thus my current view can auto wire from the child container.)

So how do you get the right container in a multiple container scenario? The standard answer is to constructor inject it, but that doesn't seem possible with the ViewModelLocator: it requires a default constructor so it can be constructed from XAML.

I'm also after a solution that works in both Silverlight 4 and WPF 4.0 since I'm working on a PRISM composite application (thus no markup extensions). I happen to be using Unity as the IOC container. Oh and the solution should work in Blend (that is, it should not prevent the creation of a new design time view model that bypasses the IoC container).

1

There are 1 best solutions below

2
On

Gennerally a child container defines a lookup hierarchy. However, your base container will have to create your child container - passing itself as a parameter.

In order to access the child container your can have a property that returns the child container - either a singleton instance or a transient (i.e. new) instance. If you want blendability you should, however, note that you the child container needs to be in your resources to bind to it at design time.

In any case you have to make sure that the instances of your ViewModels are properly cleaned up, so that no memory leaks are created.

Edit: For your pecial case this might be helpful. Although I did not had time to watch the video Laurent told me that he was demonstrating a way of dynamicaly load the view model. I hope this does help you!