Is there any difference between Service Locator Pattern and Dependency Injection Pattern ?
Asked
Active
Viewed 1,208 times
1
-
1Related: http://stackoverflow.com/questions/5460564/how-to-use-dependency-injection-and-not-service-locator – Steven May 11 '13 at 10:21
-
1Related: http://stackoverflow.com/questions/11269293/confused-over-using-ioc-container-service-locator-and-factory – Steven May 11 '13 at 10:24
-
1Service Locator is an anti-pattern that creates the illusion of loosely coupled code, but actually makes it tightly coupled (to a specific service locator implementation) and leads to a bad, unclear API (and also potentially makes testing much harder). Avoid it and use Dependency Injection wherever you can. This may sound dogmatic, but Service Locator really hardly ever has any merit. A great article on that by Mark Seemann: http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ – TeaDrivenDev May 13 '13 at 10:00
1 Answers
1
Well, they wouldn't have different names if they were the same, would they?
The Dependency Injection pattern is about injecting dependencies into what uses them - a class doesn't instantiate them itself, but they get passed in to it (either through constructor injection, property injection or as a parameter on the method that uses them normally). The caller / creator of the class has to manage it.
This is what IoC containers manage - such dependency chains. They know what dependency each class has and how to instantiate it with those dependencies.
The Service Locator pattern is different in that the service locator instantiates the dependency - however, this is normally done in the dependent class as a call to the service locator.

Oded
- 489,969
- 99
- 883
- 1,009
-
Thank you , please I have another question it's possible to use both of those patterns in the same project? – Angelika May 11 '13 at 11:14
-
2@Angelika - Yes, it is _possible_ but makes things inconsistent. Choose one or another for a project, but not both. – Oded May 11 '13 at 12:02