Frage

Assume the following Service classes:

class A {}

class B {}

class C {}

Now Class A gets a dependency on Class B. So i just inject Class B. Later in the development my Class A needs Class C too. (This could go on and on...)

Is it better to inject the Dependency Container to be able to use all services as needed. Or keep the service classes small by only injecting those classes i need?

Whats the best practice here, and why?

Currently i tend to inject each dependent service i need, mainly to see the dependency in one place (the DI annotation in the header).

Please don't close as "opinion based" this questions is for best Practice, this have to be a opinion, but when a majority of users have the same opinion then its a best practice.

War es hilfreich?

Lösung

I advise against injecting whole service container. If you do so, class dependencies get blurry (eg. you have to go through whole class code to see what dependencies this class needs) and it may lead to a mess.

Inject these dependencies you need directly. If you noticed that there are a lot dependencies in your class, it should be an alert for you that this class is doing too much (or have too many responsibilities) and you should split it (or separate responsibilities).

Andere Tipps

Don't inject the container. This is the service locator pattern, and it is usually looked at as an anti-pattern.

Reasons:

  • injecting the container couples your code to the container, which is bad because if you want to change the container you use, you have lots of classes that needs to be changed
  • it also hides the dependencies your class needs: dependencies are no longer explicit. Say I want to use your class, how do I know which dependencies I need to set in the container for your class to work?
  • what happens if you inject the container, and then your class gets a dependency but the dependency doesn't exist: exception

This is not just an opinion, there are good reasons justifying dependency injection over service location.

Injecting concrete classes is contradictory to Dependency Inversion Principle (DIP). In you case, class A (relatively higher class) should not depend on class B (relatively lower class); both should depend on an abstraction instead. So, the abstract class or an interface which is inherited or implemented by class B, should be injected into class A. The same is true for class A and class C.

IMHO, injecting the whole Dependency Container introduces an extra overhead to the injected class. So the class should be injected with those abstractions only as needed. In order to achieve that, it is also needed to design the class accordingly from the very beginning.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top