Implement MVVM Light WPF Unity Toolkit

I am using the MVVMLight toolkit for my WPF application. Now I went through the demo sample from Lauren MIX 10. The sample code is in SL and uses UnityContainer. The template provided by the MVVMLight toolkit for WPF does not use the concept of a single container. How can I use UnityContainer in WPF.

I am not right now, if my question even makes sense. I do not see any documentation on how to use ViewModelLocator. Maybe someone can provide a sample or version of the WPF Demo used by Lauren on MIX

+6
wpf unity-container mvvm-light
source share
2 answers

The way to use Unity in WPF (MVVM Light) is as follows:

I create a bootstrapper class in the root of the application, something like:

public class Bootstrapper { public IUnityContainer Container { get; set; } public Bootstrapper() { Container = new UnityContainer(); ConfigureContainer(); } private void ConfigureContainer() { Container.RegisterType<IMyRepo, MyRepo>(); Container.RegisterType<MainViewModel>(); } } 

This is my bootloader. I also register ViewModels because they are easy to create in the locator.

Then, I create a boostrapper in the ViewModelLocator constructor, and I enable each ViewModel here, for example:

 public class ViewModelLocator { private static Bootstrapper _bootStrapper; static ViewModelLocator() { if (_bootStrapper == null) _bootStrapper = new Bootstrapper(); } public MainViewModel Main { get { return _bootStrapper.Container.Resolve<MainViewModel>(); } } } 

As you can see, my ViewModelLocator is simple, it just creates a loader and resolves the ViewModel, and these virtual machines also resolve their dependencies through the container :)

There may be a better way to archive this, but this is a really good start.

+4
source share

I would recommend using the Managed Extensibility Framework. This is in .NET 4, and I switched from unity to MEF. I work great when your application grows. You can find a lot of information on it using Google. Good luck

+1
source share

All Articles