Connect ViewModel and View using Unity

In this post i want to describe the approach of connecting View and ViewModel which I'm using in my last project.

The main idea is to do it during resolve inside of unity container. It can be achived using InjectionFactory introduced in Unity 2.0

 public static class MVVMUnityExtensions
{
    public static void RegisterView<TView, TViewModel>(this IUnityContainer container) where TView : FrameworkElement
    {
        container.RegisterView<TView, TView, TViewModel>();
    }

    public static void RegisterView<TViewFrom, TViewTo, TViewModel>(this IUnityContainer container)
        where TViewTo : FrameworkElement, TViewFrom
    {
        container.RegisterType<TViewFrom>(new InjectionFactory(
            c =>
            {
                var model = c.Resolve<TViewModel>();
                var view = Activator.CreateInstance<TViewTo>();
                view.DataContext = model;
                return view;
            }
         ));
    }
}
}

And here is the sample how it could be used:

var unityContainer = new UnityContainer();

unityContainer.RegisterView<IFooView, FooView, FooViewModel>();

IFooView view = unityContainer.Resolve<IFooView>(); // view with injected viewmodel in its datacontext

Please tell me your prefered way to connect viewmodel and view.

3 Comments

Comments have been disabled for this content.