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.
Jesus rodriguez
source share