Connect ViewModel and View using Unity
Posted
by brainbox
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by brainbox
Published on Sun, 14 Mar 2010 13:47:00 GMT
Indexed on
2010/03/14
14:05 UTC
Read the original article
Hit count: 645
Silverlight
|wpf
|mvvm
|di
|Inversion of Control
|ioc
|unity
|Dependency Injection
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.
© ASP.net Weblogs or respective owner