Is a DI container a service container?

I have read a lot lately about IoC, DI, and service locators, but I have a question. Sometimes DI uses a container to call dependencies, right? But isn't a container a service locator?

I do not see the difference between the two.

+4
source share
2 answers

Yes, use or skip the DI container outside the Composition Root is a service locator. As defined by Mark Seman, composite root:

A Composition root is a (preferably) unique place in the application in which the modules are composed together.

So, as long as you use the container in this unique place, it is not a Locator.

Regarding the use of Service Locator: sometimes you can’t configure part of your application, external library or structure using only one cors composition. In this case, you can use not a container, but an abstract Factory, which is configured to create only predefined and limited resource types. Here's another Mark Seemann article, "Pattern Recognition: An Abstract Factory or a Service Locator?"

+4
source

The container registers your dependencies and can resolve them. The locator, on the other hand, uses the container to enable services.

To be able to use the container, you must have a link to it. On the other hand, the locator is usually available statically, you do not need a link to it.

A locator is considered an antipatter only because it allows you to resolve any dependency "in place" that actually makes implicit dependencies. This means that the class client is not aware of the dependency until it appears at run time.

+2
source

All Articles