This project has moved. For the latest updates, please go here.

ViewModelLocator with IOC child containers?

Apr 19, 2011 at 9:22 PM

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.

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.