Introduction
MVVM Light (mvvmlight.codeplex.com) is a very known and useful framework for building XAML based MVVM applications.
It provides its own IOC container implementation called SimpleIoc
. SimpleIoc
object is useful for simple use cases like registering and resolving instances. But, in some advanced scenarios, you want things as interception or advanced life-time management. In this case, using SimpleIoc
is not enough. You need a more reach container such as Unity (unity.codeplex.com) or Windsor Castle (docs.castleproject.org/Windsor.MainPage.ashx). Fortunately, because MVVM Light uses ServiceLocation
provided by Microsoft.Practices
, it's possible to use another container.
Using the Code
In the following paragraphs, we'll see how to use Unity. The ServiceLocator
object allows setting the container you want to use. It takes into parameter a delegate that should reference an object of type IServiceLocator
. So, for the case of SimpleIoc
, it's :
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
In order to use Unity, we'll need to implement IServiceLocator
.
public class UnityServiceLocator : IServiceLocator
{
private readonly IUnityContainer _unityContainer;
public UnityServiceLocator(IUnityContainer unityContainer)
{
_unityContainer = unityContainer;
}
public object GetInstance(Type serviceType)
{
return _unityContainer.Resolve(serviceType);
}
public object GetInstance(Type serviceType, string key)
{
return _unityContainer.Resolve(serviceType, key);
}
public IEnumerable<object> GetAllInstances(Type serviceType)
{
return _unityContainer.ResolveAll(serviceType);
}
public TService GetInstance<TService>()
{
return _unityContainer.Resolve<TService>();
}
public TService GetInstance<TService>(string key)
{
return _unityContainer.Resolve<TService>(key);
}
public IEnumerable<TService> GetAllInstances<TService>()
{
return _unityContainer.ResolveAll<TService>();
}
}
Then, we'll just set UnityServiceLocator
to the SetLocatorProvider
's parameter.
var unityContainer = new UnityContainer();
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(unityContainer));
Finally, you can create your instances using UnityContainer
instead of SimpleIoc
.
That's it !