Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a DI Container a service locator?

I've been reading alot about IoC, DI and Service Locators lately, but a question has popped into my mind. Sometimes a DI uses a container to call depencies, right? But isn't that container a service locator then?

I don't see the difference between those two.

like image 254
Alexander Cogneau Avatar asked Dec 23 '12 20:12

Alexander Cogneau


1 Answers

Yes, to use or to pass DI container outside of Composition Root is Service Locator. According to definition by Mark Seemann Compositon root is:

A Composition Root is a (preferably) unique location in an application where modules are composed together.

So, as long as you're using container in that one unique location it's not a Service Locator.

Regarding usage of Service Locator: sometimes you can't configure part of you application, external library or framework by using only one Composition Root. In this case you could use not container but Abstract Factory that configured to create only predefined and limited types of resources. Here is another article by Mark Seemann "Pattern Recognition: Abstract Factory or Service Locator?"

like image 60
Akim Avatar answered Nov 25 '22 18:11

Akim