MVVM and dependency injection

I am currently studying the MVVM pattern, and the next tutorial uses Unity for DI. I had not used DI in this way before and just wanted to clarify my thoughts on how this particular code works.

In the view, I have:

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

where the dependency attribute tells Unity to enter here. The ViewModel constructor accepts an IQuoteSource object that 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, since I never explicitly create a ViewModel using the property above. This is all processed in Unity, if so, how is this achieved?

Thanks.

+6
source share
2 answers

This has little to do with the MVVM template per se, except for the fact that a view's dependency on its ViewModel is resolved through dependency injection.

How it works is pretty simple. There are 3 simple concepts for DI:

The first declares a dependency , where some object indicates that it depends on something, either through the constructor or property (as was the case in your example using DependencyAttribute ).

The second concept is registration, in which you register the implementation of the dependencies that your objects have (in your case, you registered the implementation of IQuoteSource ). Please note: you do not need to register ViewModel, because this is not an implementation of the interface you depend on.

The third one is that it glues things that allow dependencies , where you ask the container to allow some type for you, and it goes and looks at what dependencies the object declares (in your case, you allow MainWindow , which has a dependency on the ViewModel ) , finds the correct registered implementation and resolves it. This behavior is cascaded through the resolution of the object graph (which allows the ViewModel to IQuoteSource on IQuoteSource ).

Hope this helps :)

+6
source

Is this the MainWindow to which the VM property belongs? If not, I assume that the MainWindow solution launches some kind of permission cascade, which at some point involves creating an object that has the VM property in your example.

Unity checks each object that it must resolve in the cascade for properties decorated with [Dependency] , and creates an object of a dependent property type. When he creates objects like this, he chooses a constructor that has most of the parameters that he knows how to create, and this is where IQuoteSource → RandomQuoteSource is registered.

0
source

Source: https://habr.com/ru/post/889939/


All Articles