Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing MVVM Light toolkit WPF Unity

I am using the MVVMLight toolkit for my WPF application. Now I was going through the demo sample from Lauren's MIX 10. The sample code is in SL, and makes use of the UnityContainer. The template provided by MVVMLight toolkit for WPF does not utilizes the unitycontainer concept. How can I make use of the UnityContainer in WPF.

I don't now if my question even makes sense. I do not see any documentation on how to use the ViewModelLocator. Maybe some one can provide a sample or a WPF version of the Demo used by Lauren in MIX

like image 885
xaria Avatar asked Feb 16 '11 09:02

xaria


2 Answers

The way I use Unity on WPF (MVVM Light) is like this:

I create a bootstrapper class on the application root, 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 bootstrapper. I register the ViewModels too because is easy create them in the Locator.

Next, I create the boostrapper on the ViewModelLocator's constructor and I resolve every ViewModel here, like:

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 see, my ViewModelLocator is simple, it just create the bootstrapper and resolve the ViewModel, and these VM will resolve their dependencies through the container too :)

Maybe there is a best way to archieve this, but this is a good start indeed.

like image 163
Jesus Rodriguez Avatar answered Oct 06 '22 02:10

Jesus Rodriguez


I would advise to use Managed Extensibility Framework. It's in .NET 4 and I switched myself from unity to MEF. I works very great when your app is growing. You can find lots of info on it by search using google. Good luck!

like image 36
JLaanstra Avatar answered Oct 06 '22 00:10

JLaanstra