How to use dependency injection, not a service locator

I heard people say that you should not use the Service Locator for your dependency injection. So how exactly do you inject dependencies without relying on a service locator? I want to try IoC containers, but I don’t want to land in the anti-pattern.

If you just set everything up so that there is a place where all classes always have a dependency chain for the deepest classes? (if I / makes sense at all)

I'm not right to have all of your code clutter up depending on the IoC container of choice, right?

So where do you β€œuse” your container (for reconnecting)? And how do you resolve it to solve everything, how deep is your code? Is this part of designing the entire correct path using interfaces through each layer to the front layer?

Or am I just missing the point?

Let me remind you that I just do not want to fall into the anti-pattern and need advice / heads-up.

+3
source share
1 answer

If you just set everything up like that, is there one place where all classes always have a dependency chain with the deepest classes? (if I / what makes sense at all)

Yes, this is called the root of the composition of your application, and where you would configure your IoC container and resolve your root type.

It's wrong to have all your code littered with IoC dependencies a container of choice, right?

Correctly, it’s better not to pass references to your IoC container around your types, as this will make them less reusable and associate types with the concept of IoC containers in general.

So where do you β€œuse” your container (for reuse)? And how do you allow it, since how much does your code go? Is it part of designing the entire correct path using the interfaces through each layer up to the front layer?

You should use your container at the root of your composition and anywhere in your code that should create instance types (i.e. from factory) through the container (usually to support a dependency chain).

Many IoC containers can create these factory types for you, so you only need to pass, for example. IMyFactory as a dependency or in some IoC container, a Func<IMyService> . This means that you do not need to create factory types that are dependent on your IoC container.

In terms of using interfaces, the dependency inversion principle says that you should depend on abstractions, not nodules, so you will need to consider your code with this concept in mind if you want to take a dependency injection.

+6
source

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


All Articles