Dependency Injection is a method of wiring up classes together externally to the definition of the class.
For instance, if class
BusinessObject calls class
SQLServer thorugh interface
IDatabase, a direct coupling of the two classes will exist because class
BusinessObject still explictly instantiates class
SQLServer by name (i.e.
IDatabase db = new SQLServer().)
If it's later desired that class
BusinessObject use a different implementation of IDatabase, it has to be modified to specify a different class. Dependency Injection is a methodology by which class
BusinessObject can call different implementations of
IDatabase without having to modify class
BusinessObject. It can be as simple as providing an additional constructor to class
BusinessObject which takes on an externally created object implementing
IDatabase. Or it can be as sophisticated as a Dependency Injection framework that provides a means of wiring up classes through an external configuration file.
Inversion of Control
Dependency Injection goes hand-in-hand with the concept of Inversion of Control (IoC), which is a method of having a framework instantiate the classes on behalf of the application, rather than the other way around (thus inverting the control of who creates objects.) IoC Frameworks also include Dependency Injection facilities so that the framework provides the means of both creating the object and wiring them up.
Methods of Dependency Injection
Dependency Injection By Hand
Unity Application Block
The Unity Application Block is Microsoft's implementation of Dependency Injection and Inversion of Control. See Unity Application Block
Caste Project is a mature and feature rich Dependency Injection and Inversion of Control. See:
- MSDN article that details the castle project's container: http://msdn2.microsoft.com/en-us/library/aa973811.aspx)
- A very good introduction on Dependency Injection, using Castle Project: http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart1.aspx
IoC/Dependency Injection containers have the advantage of creating decoupled classes and components (see Benefits of Decoupled Components.) This helps with dependencies in the build system and with unit testing a great deal. In addition, it makes the code more easily modifyable because swapping out new implementations becomes quite easy. Developers using IoC frameworks don't think in terms of providing plug-ins for their applications because every class in the software becomes a plug-in by definition.
- Stefano’s Linotype article on the first use of the term Inversion of Control
- Another good article on Dependency Injection: The Dependency Injection Pattern – What is it and why do I care?