Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Dependency injection vs service locator

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

like image 828
javaguy Avatar asked Aug 30 '12 21:08

javaguy


People also ask

What is the difference between Service Locator and dependency injection?

To implement the IoC, you have the choice of two main patterns: Service Locator and Dependency Injection. The Service Locator allows you to "resolve" a dependency within a class and the Dependency Injection allows you to "inject" a dependency from outside the class.

When should dependency injection be used?

More specifically, dependency injection is effective in these situations: You need to inject configuration data into one or more components. You need to inject the same dependency into multiple components. You need to inject different implementations of the same dependency.

Should I use service locator?

Service Locator is a well-known pattern, and since it was described by Martin Fowler, it must be good, right? No, it's actually an anti-pattern and should be avoided.

What is dependency injection pattern How does it compare to service registry pattern?

A registry pattern has no control over the lifetime of the instances, but injecting a DI container into the application gives the DI container explicit control over the instance lifetimes. The latter can give each type a different lifetime, the former are always singleton lifetime regardless of the type requested.


1 Answers

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.
like image 166
Aravind Yarram Avatar answered Oct 21 '22 03:10

Aravind Yarram