Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection: should I inject everything or use a service locator for some objects?

I'm currently refactoring my Zend Framework based PHP library from using a service locator to (constructor) dependency injection (DI). I feel that it improves my code a lot, but I'm not sure if I should inject all dependencies. A service locator seems easier for dependencies which are used a lot and are unspecific. I have the following dependencies which I still access using a service locator:

  1. A Zend_Translate object (I need to translate messages everywhere).
  2. A Zend_Locale object (stores the current language)
  3. A Zend_Config object (a lot of things are configurable by ini-file)
  4. Instances of utility classes (for array and string manipulation)

If I injected these dependencies, they'd clutter my constructors and distract from the specific dependencies. For testing, I can just set up these dependencies in my service locator before running the tests. The pragmatist in me says I'm doing just fine, but the purist says I should go all the way with DI.

Would you recommend DI for these types of objects or not?

like image 772
aimfeld Avatar asked Mar 15 '12 09:03

aimfeld


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.

Which service is a benefit of using dependency injection?

A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.

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.


1 Answers

When it comes to the concern about cluttering the constructors, it's most likely a code smell that the classes are violating the Single Responsibility Principle. Constructor Injection is very beneficial here because it make this much more obvious.

Some people also worry about injecting dependencies which are only rarely used, but that's not a problem either. When it comes to creating object graphs, performance is rarely a problem, and even if it is, the Virtual Proxy pattern can fix it.

In short, there's no reason to ever use a Service Locator. There's always a better alternative that involves proper inversion of control.

like image 75
Mark Seemann Avatar answered Oct 25 '22 02:10

Mark Seemann