Simple Dependency Injection

When you are working in the real world (especially on enterprise software) you will find yourself having to support and enhance an older code base. These code bases can vary quite considerably in quality. In the worst case you have legacy code that contains no unit tests. When you need to maintain and enhance this code you really should try to get some tests wrapped around the code, but this is easier said than done.

The code may contain lots of hard coded dependencies to objects that makes adding in clean, isolated unit tests difficult. These hard coded dependencies may access the file system, make database calls or access any other external resources making writing isolated tests difficult.

What do I mean by a hard coded dependency? Well, take a look at the following simple example.

using System;

namespace HardDependency
{
    public class ExampleClass
    {
        public string GetText
        {
            get
            {
                return "Hello, I am a hard dependency.";
            }
        }
    }

    public class MyProgram
    {
        public void DoSomething()
        {
            ExampleClass example = new ExampleClass();
            Console.WriteLine(example.GetText);
        }
    }

    class Program
    {
        static void Main()
        {
            MyProgram program = new MyProgram();
            program.DoSomething();
            Console.ReadLine();
        }
    }
}

In this simple example we have a class called ExampleClass. This class has a property that returns a string. The class MyProgram has a method called DoSomething() that creates an instance of ExampleClass and calls the property to display the returned string. You may be thinking that nothing untoward is happening here, but what you see here is an example of a hard dependency, or coupling, between MyProgram and ExampleClass. Lets imagine ExampleClass is doing something much more complicated like reading data from a database. If you try to write a unit test to cover the functionality¬† of the DoSomething() method in MyProgram then that unit test will be making a database call. This is not a unit test. It may run fine on your development PC, but when you try to run these unit tests on your build server, it will also try to make a call to the database. A build server shouldn’t have access to an applications database. Also, what if that call to the database changes the state of the data, so that the next time you run the test, the data has changed, so the test fails. This is not a good situation as you now not only have tight coupling in your code, but you are also coupled to the state of the data in your database.

%d bloggers like this: