Reputation: 18308
We use an MVC architecture with a model consisting of a BLL and DAL.
So we develop "modules" for our system and the particular one I am implementing makes use of alot of the same dependencies. One class in particular has 20 dependencies. Currently the default constructor is creating a default concrete implementation, and we also have a second constructor [that the first one uses] that allows one to inject there own dependencies (i.e. testing.)
20 constructor arguments seems like a pretty nasty code smell. The other annoying thing is that often when I starting to add common functionality, I need to go add constructor code and fields in every class often repeating the same kinds of code over and over again.
An IoC container seems like a natural solution to this, but the problem is how far do I go? Do I include the DAL dependencies and the BLL dependencies? What about "helper" or "service" dependencies? It seems like at a certain point I am just recreating the "namespace" structure with the ability to reference my classes like static classes at which point I question what I am actually gaining.
I am having trouble thinking through this. Does anyone have an elegant solution or advice?
Upvotes: 0
Views: 809
Reputation: 22255
If you go the IoC route (which I recommend) I would include all your dependencies in the container.
The benefit is that you never have to worry about creating those dependencies, even if there are a ton of them many layers deep.
e.g ClassA takes in 4 other classes in it's constructor, each of those takes in two others in theirs, and each of those takes in at least a DAL reference.
In that case you just need to reference the IoC in your highest-level layer (the "composition root"), which could be your UI, and say "give me an instance of object A", then the IoC will automagically instantiate the other 20 instances for the various dependencies needed to construct the object graph.
Your classes no longer need to worry about how to create their dependencies, if they need something they just stick it in the constructor and the IoC will ensure it gets it.
I would also comment that 20 dependencies in one class is a definite code smell even if you're using IoC. It usually indicates that class is doing far too much stuff and violates the Single Responsibility Principle.
Upvotes: 7