I think dependency injection is a very effective technique to write more modular and generally better structured programs. It vastly improves the design of an application encouraging decoupled and highly testable components.
What I like less is that often programmers who dependency injection also use a container. They use it to wire all the components up using some sort of magic, usually through reflection.
Magic always comes with a price
The use of magic is exactly the reason why I don’t like containers. They save you from writing some boilerplate code, which is never the hardest thing you’ll write in an application with a decent architecture, and doing so they’ll make you pay the price of losing several extremely useful features.
Here are some, just to name a few:
- would you like the compiler to show you an error when you miss something? Sorry, this is not going to happen. The container moved wiring your application up at runtime. You’ll get an exception instead.
- do you like when your IDE helps you finding where constructors are used? I do, but the price for not writing some code is that the IDE cannot help me with that. The code is not used anywhere as far as it can tell.
Mark Seeman shows clearly the trade offs between not using a container at all, using it with explicit registrations and using it by convention. The first case is simple and valuable. The second is quite sophisticated and pointless. He claims that the third is sophisticated but valuable.
When you use a container in the good way, you get something that is low maintenance at the price of using a technique that is hard to learn and weakly typed. That’s definitely not for me, and that’s the reason why I agree with yegor256 when he says that DI-containers are code polluters. I think that there is something wrong with your application if you really need to use a container to save you from the burden of putting all the components of your application together. You probably should have a look at how your application is structured rather than hiding the issues under the carpet and pretending that the problem is not there.
This post was originally published on mariosangiorgio.github.io