Dependency Injection is about Components...
Posted by Nicholas Blumhardt | April 09, 2007 17:01
…as opposed to classes. DI works best at a level of abstraction higher than that of individual classes.
Many of the dependency injection examples you’ll find in a typical web search or documentation-trawl neglect to mention this key fact. The biggest benefit of dependency injection is loose coupling. Loose coupling is very important between the large-scale components of a system, but can be an anti-goal at the class level where high cohesion is a valid quality to pursue. The creation of objects in a loose coupling scenario should be delegated to a builder, such as an IoC container, but in a high-cohesion scenario you’re really looking more towards a closely-related class to do the creation and configuration of an object.
The ‘factory’ lifecycle model options supported by many containers could very easily encourage a proliferation of ‘inside out’ applications where the IoC container has responsibility for creation of far too many classes of objects. (The example I just saw described ‘Button’ as an example of a class that would use a factory lifecycle.)
The responsibilities of the container should be restricted to wiring together the bigger pieces, such as network interfaces or data layers, that can feasibly be used independently of each other. Putting the responsibilities associated with creating other, tightly-integrated lower-level classes into the container as well gives the container ‘responsibility bloat’ in my opinion. I doubt the authors of the existing dependency injection tutorials intended any different, but I guess it is hard to come up with examples of valid components with factory-style lifecycles.
Disclaimer: These articles represent the opinions of the authors and may not match the official position of Ubik Systems Pty. Ltd. Confirmation should be sought on all matters involving professional advice.
