开发者

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 sampl开发者_Go百科e or a WPF version of the Demo used by Lauren in MIX


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜