Reputation: 30731
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.
Upvotes: 2
Views: 85
Reputation: 49553
Don't inject the container. This is the service locator pattern, and it is usually looked at as an anti-pattern.
Reasons:
This is not just an opinion, there are good reasons justifying dependency injection over service location.
Upvotes: 1
Reputation: 3950
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.
Upvotes: 0
Reputation: 11374
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).
Upvotes: 1