Implement IoC container?

I study all morning trying to find best practices for accessing your IoC. After adding the constructor installation to your classes, you still need to access the contianer from classes that can be deep in the graph of application objects. In my case, I am doing MVVM in WPF, and some of my view models should create other view models, and they will use the container for this. But the question is where can they get the container. Does it make sense to enter and transmit it? Is it possible to make it an injection singleton? Is a factory that caters for one tone more suitable?

What are the options and trade-offs?

Update

I found this wonderful Matt Hinze talk that spans a lot of IoC land: http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/04/08/inversion-of-control-in-action-by-matt-hinze- north.aspx

It seems like one answer is to use the scan function and save the IoC configurations in the registries in each assembly, and then when scanning these registry configurations will be added.

Are there any other review approaches? Especially considering that Matt demonstrated the use of the ServiceLocator pattern, while Mark Siman calls it an anti-pattern. Note that Matt cautioned against using the template and that the Mark Locator definition (http://blog.ploeh.dk/Trackback.aspx?guid=5f05c086-295b-41e5-a50a-ed0cd77ac4bd) looks different than what Matt showed .

+6
source share
2 answers

Instead of injecting your actual instances of ViewModel that will be complex, as you say, you can inject factories into your best ViewModels. This is similar to a service locator pattern, expect factories (or service providers or what you have) to be more specific in what they can deliver.

+2
source

One way is to use a ServiceLocator that points to a specific container. Since the locator is usually displayed as a singleton, you get your container for free from anywhere in the code.

For example, in Unity, it will be similar to

 // configure the locator somewhere early UnityServiceLocator locator = new UnityServiceLocator( container ); ServiceLocator.SetLocatorProvider( () => locator ); ... // get the container anywhere var container = ServiceLocator.Current.GetInstance<IUnityContainer>(); 

Discussing whether a locator is antipattern is beyond the scope. In my opinion, this is at least no more "antipattern" than the whole IoC.

0
source

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


All Articles