开发者

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 speci开发者_如何学运维fic 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.


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 :)


Is it MainWindow which the VM property belongs to? If not I'm assuming that resolving a MainWindow starts some sort of resolve cascade which at some point includes creating the object which has the VM property in your example.

Unity examines each object it has to resolve within the cascade for properties decorated with [Dependency], and creates an object of the dependent property type. When it creates objects like this it picks the constructor which has the most parameters it knows how to create, which is where your registration of IQuoteSource -> RandomQuoteSource comes in.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜