Reputation: 1274
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.
Upvotes: 6
Views: 481
Reputation: 8679
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?"
Upvotes: 4
Reputation: 48314
Container registers your dependencies and can resolve them. Locator on the other hand uses a container to resolve services.
To be able to use a container, you have to have a reference to it. On the other hand, the locator is usually available statically, you don't need a reference to it.
Locator is considered an antipattern just because it lets you resolve any dependency "in place" which in fact makes dependencies implicit. This means that the class client is not aware of the dependency until it shows up in the run time.
Upvotes: 2