6

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.

1

2 Answers 2

4

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?"

1
  • I was writing a comment to explain why I did not completely agree with your answer, but after rereading your answer I discovered that we probably think the same, but that you forgot a single word. See my update.
    – Steven
    Dec 24, 2012 at 10:05
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.