Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Dependency Injection constructor madness?

I find that my constructors are starting to look like this:

public MyClass(Container con, SomeClass1 obj1, SomeClass2, obj2.... ) 

with ever increasing parameter list. Since "Container" is my dependency injection container, why can't I just do this:

public MyClass(Container con) 

for every class? What are the downsides? If I do this, it feels like I'm using a glorified static. Please share your thoughts on IoC and Dependency Injection madness.

like image 782
JP Richardson Avatar asked Mar 10 '10 20:03

JP Richardson


People also ask

Which constructor does dependency injection use?

Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.

Why constructor based dependency injection is better?

Constructor injection helps in creating immutable objects because a constructor's signature is the only possible way to create objects. Once we create a bean, we cannot alter its dependencies anymore.


1 Answers

You are right that if you use the container as a Service Locator, it's more or less a glorified static factory. For lots of reasons I consider this an anti-pattern (also see this excerpt from my book).

One of the wonderful benefits of Constructor Injection is that it makes violations of the Single Responsibility Principle glaringly obvious.

When that happens, it's time to refactor to Facade Services. In short, create a new, more coarse-grained interface that hides the interaction between some or all of the fine-grained dependencies you currently require.

like image 195
Mark Seemann Avatar answered Oct 21 '22 15:10

Mark Seemann