I first encountered dependency injection, a pattern that implements inversion of control for resolving dependencies, when I was investigating the web application frameworks available for Java and decided to go with Spring (of course J2EE has dependency injection as well). When you start off with a golden hammer like dependency injection, suddenly every one of your software development challenges looks like a nail. And, as you would expect, all the books and documentation encourage this, although I suspect not consciously.
Dependency injection is a fantastic tool if you have multiple components you want to bring together to form a myriad of different applications. The perfect example is of course the Spring framework, because it is exactly that and dependency injection works very well in that context (no pun intended).
However, dependency injection should not be your default pattern for every project and if you are using it in a project, you should only use it when it’s really needed. Don’t load every object in your application into the container, you don’t need to.
Dependency injection is great for reducing the dependencies between components in your application and for allowing you to plug custom components into frameworks, as well as many other things, but one way or another it adds a further level of complexity to your application. Most dependency injection frameworks use either one or more files containing something like XML or a declarative method using something like annotations directly on classes to build the container at runtime.
Each method has its own drawbacks. With XML files you have a second place, other than your code, to understand and potentially to debug. With the declarative method you have no easy overview of exactly what is going into the container at runtime and you have to be careful about objects being instantiated and injected unintentionally.
And of course over full containers can result in very slow application startup and tests. If you have to fire up the dependency injection runtime and load objects into it every time you run a test it makes your tests slower and more complicated. Then you won’t run them or maintain them.
So what’s the solution? As the ‘Effective’ series of programming books are so fond of saying, be judicious. When you’re tempted to put an object into your container, first consider whether it really needs to be there. It might be better served, for example, being orchestrated with other objects behind a facade which is loaded into the container if necessary. That way you’ll find yourself with simpler code which is easier to maintain and test and it may just even perform a bit better at runtime.