Fowler has a good comparison between the two in his handling of the control containers and the Injection Dependency Heading . In his final thoughts, he says:
Dependency injection is a useful alternative to Service Locator. when application classes for applications two are approximately equivalent, but I think that the service locator has a slight advantage due to its more direct behavior. However, if you are creating classes for being used in several applications, then dependency injection is a better choice.
You can find more viewpoints and comparisons in here.
For DI:
- It's easier to determine what dependencies a component has - look at the constructor.
- The component is not dependent on the Service Locator, so there is no problem if the component is used with another framework.
- DI can simplify testing, but a good service locator mechanism will do equivalent performance
Against DI:
- Itβs more difficult to debug and understand.
- .