Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM and Dependency Injection

I am currently learning the MVVM pattern, and the tutorial I am following uses Unity for DI. I haven't really used DI in this way before and just wanted clarification of my thoughts on how this specific code works.

In the View I have:

private ViewModel vm;

    [Dependency]
    public ViewModel VM
    {
        set
        {
            vm = value;
            this.DataContext = vm;
        }

    }

where the dependency attribute is telling Unity to inject here. The ViewModel constructor takes an IQuoteSource object which is registered with Unity as such:

        IUnityContainer container = new UnityContainer();
        RandomQuoteSource randomQuoteSource = new RandomQuoteSource();
        container.RegisterInstance<IQuoteSource>(randomQuoteSource);
        MainWindow window = container.Resolve<MainWindow>();
        window.Show();

How exactly does this work, as I am never explicitly creating an object of the ViewModel using the property above. Is this all handled within Unity, if so how does it achieve this?

Thanks.

like image 545
Darren Young Avatar asked Jun 07 '11 10:06

Darren Young


1 Answers

This doesn't have much to do with the MVVM pattern per se, other than the fact that the view's dependency on its ViewModel is resolved via dependency injection.

For how this works, it's pretty simple. There are 3 simple concepts for DI:

The first is declaring a dependency, where some object specifies that it depends on something, either via a constructor or a property (which was the case in your example, using the DependencyAttribute).

The second concept is registration, where you register an implementation of the dependencies your objects have (in your case, you registered an implementation of the IQuoteSource). Note that you didn't have to register the ViewModel, because it's not really an implementation of an interface that you depend on.

The third is what glues things together, which is resolving the dependencies, where you ask the container to resolve some type for you, and it goes and looks at what dependencies that object declared (in your case, you're resolving the MainWindow which has a dependency on the ViewModel), finds the right registered implementation and resolves it. This behavior cascades through the resolution of the graph of objects (which resolves the dependency of the ViewModel on the IQuoteSource).

Hope this helps :)

like image 138
AbdouMoumen Avatar answered Oct 11 '22 14:10

AbdouMoumen