I saw the light Connect ViewModel and View using Unity - Alexey Zakharov's Blog

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.

Published Sunday, March 14, 2010 7:47 PM by brainbox

Comments

# Links (3/14/2010) &laquo; Steve Pietrek-Everything SharePoint/Silverlight

Pingback from  Links (3/14/2010) &laquo; Steve Pietrek-Everything SharePoint/Silverlight

# re: Connect ViewModel and View using Unity

Monday, March 15, 2010 2:23 AM by thangchung

Hi Alexey, your way to connecting the view and the viewmodel is good.

But if I use User control for render content.

How to do it?. Maybe I must write this those class with generic that can accept the class control inside namespace System.Web.Mvc.ViewUserControl?

IMHO

# re: Connect ViewModel and View using Unity

Monday, March 15, 2010 4:34 AM by Alexey Zakharov

Hi thanchung. I'm speaking about WPF Silverlight MVVM pattern not ASP.NET MVC.

# re: Connect ViewModel and View using Unity

Monday, March 15, 2010 6:54 AM by thangchung

@Alexey: Sorry about that. I have mistake

Leave a Comment

(required) 
(required) 
(optional)
(required)