Introduction
This article is actually part 3 of an introductory series ofarticles on Microsoft’s Composite Application Block (CAB) and SmartClient Software Factory (SCSF). However, this particular article willonly talk about dependency injection in general terms and not discussthe CAB/SCSF. Part 5 of the series will address dependency injection inthe CAB. Part 4 of the series expands the discussion here by talking about inversion of control (IoC) and dependency inversion.
Dependency Injection
Dependency injection as a general concept is explained far better than I could do it by Martin Fowler at http://www.martinfowler.com/articles/injection.html.However, in short it is a means of allowing a main class to use asecond, dependent class without directly referencing that class. Someexternal entity will provide the second class to the main class atruntime – it will ‘inject’ the ‘dependency’. Obviously to be useful thesecond class will need to implement an interface that the main classknows about.
The aim of this is to let us change the behaviour of our classstructure by changing which second class is injected into the mainclass. Because the main class has no hard dependency on the secondclass this can be done at runtime. Thus our code is very flexible, easyto modify and loosely coupled.
Class Diagram
The class diagram looks something like this:

MainClass contains a reference to an object that implementsIDependentClass, and can thus call the DoSomethingInDependentClassmethod on that object. DependentClass1, DependentClass2, andDependentClass3 implement the interface.
Some client code will then create the appropriate dependent classand tell the main class to use it (via the interface). It’s easiest tounderstand this via some example code, which I’ll demonstrate below.
Strategy Pattern?
In many ways this is the classic Gang of Four Strategy pattern witha twist. The class diagram above is very similar to the usual one givenfor the strategy pattern: see http://www.dofactory.com/Patterns/PatternStrategy.aspx(don’t worry if you don’t know the strategy pattern at this stagethough). The difference is that with dependency injection exactly whichclass is going to be provided as the dependency (strategy) is oftenleft to configuration at runtime. That is, it can be abstracted out ofthe code entirely.
In the Spring framework, for example, XML configuration files can beused to specify which class gets created and used. This is an extremeexample of deciding which class to use at runtime: you can change thedependencies without changing the compiled code at all.
However, there are some reasons for not using external configurationfiles to specify these dependencies: it makes it difficult to debug,and you’re probably not going to want to change application behaviourvia a configuration file in any case. Dependency injection frameworksin general will allow you to specify your injection in code (Springallows this).
Dependency Injection Example
We can easily create an example that does this using .NET. Full code for all these examples is available for download.
Firstly we create an interface that will be used to call our dependent class:
public interface IDependentClass{void DoSomethingInDependentClass();} Then we create dependent classes that implement this interface to dosomething. Which one of these classes will actually be used will onlybe decided at runtime based on a setting in the App.Config file:
public class DependentClass1 : IDependentClass{public void DoSomethingInDependentClass(){Console.WriteLine("Hello from DependentClass1: I can be injected into MainClass");}} public class DependentClass2 : IDependentClass{public void DoSomethingInDependentClass(){Console.WriteLine("Hello from DependentClass2: I can be injected as well, just change App.Config");}}Now we create a class that will use the dependent classes, callingtheir functionality via the interface. This ‘main’ class has noknowledge of the dependent classes types, only of the interface thatthey implement:
public class MainClass{IDependentClass dependentClass;public IDependentClass DependentClass { get { return dependentClass; } set { dependentClass = value; } } public void DoSomething(){dependentClass.DoSomethingInDependentClass();}} Now we need some code that will use this structure. Clearly we needto instantiate the main class and tell it (using the interface) whichdependent class to use. We can then call the functionality on the mainclass.
static void Main(string[] args){// Get the correct dependency based on configuration fileIDependentClass dependency = GetCorrectDependency(); // Create our main class and inject the dependencyMainClass mainClass = new MainClass();mainClass.DependentClass = dependency; // Use the main class, the method references the dependency// so behaviour depends on the configuration filemainClass.DoSomething(); Console.ReadLine();} Finally we need some code in GetCorrectDependency() that decideswhich dependent class we are going to use, and instantiates it. We dothis by examining the ‘ClassName’ setting in App.Config, andinstantiating that using Activator.CreateInstance:
static IDependentClass GetCorrectDependency(){string classToCreate = System.Configuration.ConfigurationManager.AppSettings["ClassName"];Type type = System.Type.GetType(classToCreate);IDependentClass dependency = (IDependentClass)Activator.CreateInstance(type);return dependency;} The App.Config file is as below:
<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="ClassName" value="DependencyInjection.DependentClass1" /> </appSettings></configuration>
So we can compile this code and run it as above and it will outputthe message in DependentClass1. If we then just change theconfiguration file so that the ClassName value isDependencyInjection.DependentClass2 and re-run the code will output themessage in DependentClass2.
Note that what is powerful about this code is we could write aDependentClass3, with new behaviour, and use it by changing theconfiguration file without the need to change any of the existing code.
Types of Dependency Injection
Martin Fowler’s article talks about three different types ofdependency injection: constructor injection, interface injection andsetter injection. The example above uses setter injection: we give the main class its dependency via a setter in the line:
mainClass.DependentClass = dependency;
In constructor injection we give the main class its dependency inthe constructor. With interface injection we define another interfacethat the main class will implement that sets the dependency.
I have reworked the example above for both constructor injection and interface injection. As you can see these are relatively trivial changes in this simple example.
Full C# code for these examples is available.
This series of articles is continued in part 4, which discusses inversion of control.

