views:

299

answers:

4

I've been using manual constructor injection DI for a little bit now. One thing that I notice is that my constructors are starting to get rather long.

I have a class that depends on a bunch of little objects - anywhere between 6 and 10 sometimes. As I continue to break my application into smaller chunks, I could see this number increasing over time. Is this a common problem?

Obviously this is going to depend a great deal on the project. However, the basic question is this:

When do you start to get uncomfortable with the number of dependencies that a class has? What are some strategies that you use to reduce these dependencies?

+6  A: 

This may be a sign that the class with the 6-10 dependencies itself needs to be refactored.

Jacob B
+2  A: 

I would think no more than three or four. If you are getting more than that, I would start thinking about how well you are abstracting your concerns. A single repository object, for example, should fulfill all of your data retrieval needs within the class in question.

Robert Harvey
Presumably, if an object requires access to a database and some way to communicate externally (say, Repository and IO) that's already 2 dependencies out of the allotted 4. Besides - isn't one of the side-effects of making sure that each class has a single responsibility (single concern) going to result in more classes rather than fewer? Ultimately, there needs to be a class that can orchestrate all these smaller pieces...and that class will have many dependencies in order to function.
Runcible
@Runcible, quite correct. And if the consolidation you describe takes place, you will indeed have fewer things to inject into the constructor. What you are describing BTW is an Inversion of Control container (like Windsor, for example).
Robert Harvey
A: 

You may also want to see if any of the parameters to your constructor should be combined into a single class as well (assuming that the parameters make sense as a class).

It might also be that you want to look at using the ServiceLocator pattern for some of your dependencies. This is particularly true if you're having to pass the dependencies down a long chain of constructors.

Rob Scott
The Service Locator pattern is sort of in opposition to the Dependency Injection principles. Service Locator violates the Law of Demeter: http://www.youtube.com/watch?v=RlfLCWKxHJ0
Runcible
+2  A: 

Runcible,

Here is a link to the Castle Windsor project. It is an Inversion of Control container. These containers allow factory classes to collect your dependencies together and inject them as a single object into your constructor.

http://www.castleproject.org/container/index.html

I have heard good things about Windsor. Spring also makes an IoC container, and there are others.

Robert Harvey