javaguy
javaguy

Reputation: 4442

When to use Dependency injection vs service locator

When will you use dependency injection? Is there any overwhelming benefit of using dependency injection?

Upvotes: 5

Views: 1708

Answers (1)

Aravind Yarram
Aravind Yarram

Reputation: 80194

Fowler has good comparision between the two in his Inversion of Control Containers and the Dependency Injection pattern Heading. In his concluding thoughts, he says

Dependency Injection is a useful alternative to Service Locator. When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.

You can find more view points and comparisons in here

For DI:

  • Easier to determine what dependencies a component has - look at constructor.
  • Component does not have dependency on Service Locator so there is not a problem if the component is used with a different framework.
  • DI may make testing easier but a good Service Locator mechanism will make stubbing equally feasible

Against DI:

  • Harder to debug and understand.
  • Component cannot request extra services from injector once it had been configured.

Upvotes: 5

Related Questions