When comparing Service Locator vs Dependency Injection, the Slant community recommends Service Locator for most people. In the question“What are the best Inversion of Control mechanisms? ” Service Locator is ranked 1st while Dependency Injection is ranked 3rd. The most important reason people chose Service Locator is:
By selecting which items are in the service locator, applications can optimize themselves during run-time.
Ranked in these QuestionsQuestion Ranking
Pros
Pro Applications can optimize themselves on run-time
By selecting which items are in the service locator, applications can optimize themselves during run-time.
Pro More decoupled code
Since the class doesn't have to know anything about the outside world, everything is more decoupled. If your class would have to fetch its own dependencies then it would have to know where to find them, and as a result, it would have to know about the larger application.
Pro More flexible code
Since your class doesn't have to know about the concrete implementation of the dependencies, it makes them very flexible.
Cons
Con Hides class' dependencies, causing run-time errors instead of compile-time errors
Service Locator hides the class' dependencies, causing run-time errors instead of compile-time errors when dependencies are missing.
Con Very easy to use it incorrectly by coupling nearly all code with it
The wrong approach to Service Locator introduces an unnecessary dependency between the class and the container. It conceals what the dependencies really are as you have to check through the detail of the code to figure out what’s being resolved.
Con Steep Learning Curve
Significant effort is needed to grasp DI and use it correctly.