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.

What we need to do is stub out the functionality in ExampleClass so that the call is never made to the database and we can control what ExampleClass returns. We are, after all, only testing the functionality of the DoSomething() method on the MyProgram class.

There are 2 things we can do. We can either use a Mocking framework, or we can use dependency injection. A mocking library is fine if you just want to get tests around some old code but you are not going to re-write or extend the code yet. But I feel that if you do use a mocking library, you should only really make it a temporary thing. Have a plan for refactoring the code to use dependency injection. In the end you will end up with cleaner, better structured code.

The first example I will show of dependency injection is called, Constructor Injection. Take a look at the following example.

using System;

namespace ConstructorInjection
{
    public interface IExampleClass
    {
        string GetText { get; }
    }

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

    public class ExampleClass2 : IExampleClass
    {
        public string GetText
        {
            get
            {
                return "Hello, I am an injected dependency.";
            }
        }
    }

    public class MyProgram
    {
        private IExampleClass _exampleClass;

        public MyProgram()
        {
            _exampleClass = new ExampleClass();
        }

        public MyProgram(IExampleClass injected)
        {
            if (injected == null)
            {
                throw new ArgumentNullException("injected");
            }

            _exampleClass = injected;
        }

        public void DoSomething()
        {
            Console.WriteLine(_exampleClass.GetText);
        }
    }

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

            MyProgram program2 = new MyProgram(new ExampleClass2());
            program2.DoSomething();

            Console.ReadLine();
        }
    }
}

In the example above, ExampleClass contains the original functionality that we want to stub out, so an interface called IExampleClass is created that contains the GetText property. Most IDE’s have ExtractInterface as part of their refactoring tools.

Once this interface is created, a new ExampleClass is created called ExampleClass2. This class also implements the same interface as ExampleClass, but GetText returns a different message.

The class MyProgram has been extended a little. The class now stores a reference to an IExampleClass interface. The default constructor  on MyProgram creates an instance of ExampleClass and stores it. Therefore if you create an instance of MyProgram using the default constructor, you will get exactly the same functionality as before when you call DoSomething().

If you create an instance of MyProgram but use the overloaded constructor, you can pass in an instance of ExampleClass2. This instance will get stored in the class instead as it implements the same interface as ExampleClass, so when you call DoSomething(), you get a different message returned.

This simple example illustrates the basic principal of constructor injection to substitute functionality. If we go back to our hypothetical example where ExampleClass returns data from a database, the ExampleClass2 object could return some pre-determined data instead and not make any calls to the database.  The unit test doesn’t care where the data comes from. It is testing what happens with that data once it is returned.

Constructor injection is a great technique for breaking tight coupling in your code, but if the classes you are working with are very large you may get to the point where you have lots of stubs being passed into your constructor. This starts getting quite untidy after 5 parameters are being passed. You could break them out into a separate containing class, but this can still feel quite messy.

There are a number of open source Dependency Injection frameworks that you can reach for at this point. Frameworks like NHibernate, Castle Windsor, Unity, and Structure Map offer many powerful features and are very good at what they do, but I find they are quite heavy handed when all you want to do is break a few dependencies. I have even seen developers get into a right muddle when using a powerful DI framework. Ever tried unpicking Unity when it’s features have been abused by an over eager developer? It’s not nice! I am not dismissing these frameworks at all. In fact I am a big advocate of them, but I prefer to get the team to use them when working on code that is already under control, or on a nice new green field project.

What I normally do when breaking dependencies on a large project is write a very basic dependency injector. For very basic functionality, they really are not that complicated. Here is an example of a simple one that I use fairly often.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DependencyInjection
{
    public static class ObjectActivator
    {
        private readonly static Dictionary<string, Type> _objectStore =
                new Dictionary<string, Type>();

        public static int Count
        {
            get
            {
                return _objectStore.Count;
            }
        }

        public static void AddObject(string name, Type objectType)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            _objectStore.Add(name, objectType);
        }

        public static bool Contains(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            return _objectStore.ContainsKey(name);
        }

        public static object GetInstance(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (!Contains(name))
            {
                throw new InvalidOperationException("name");
            }

            return Activator.CreateInstance(RetrieveObject(name));
        }

        public static void ClearRepository()
        {
            _objectStore.Clear();
        }

        private static Type RetrieveObject(string name)
        {
            return _objectStore[name];
        }
    }
}

I won’t go into it line by line, but essentially all it is, is a dictionary of string mappings to a ‘Type’ object. I used strings as the key as I want to completely decouple the types registered into the dictionary, so when retrieving an instance of a type, I refer to it by name. You could use something else as the key if you wanted, but I tend to use strings. It is down to personal preference.  AddObject() registers a Type to a name and GetInstance() uses the Activator.CreateInstance() method to construct an instance of the type when an instance is requested.

The idea with this class is that by using it, when your program starts up, you register the concrete implementations of the classes you want to inject. Then, when you need to create an instance of that Type, you do so by name and therefore the class requesting the instance never see’s the concrete object, only the interface. Here is a simple example of using it.

using System;

namespace DependencyInjection
{
    public interface IExampleClass
    {
        string Name { get; }
    }

    public class ExampleClass : IExampleClass
    {
        public string Name
        {
            get
            {
                return "ExampleClass";
            }
        }
    }

    public class ExampleClass2 : IExampleClass
    {
        public string Name
        {
            get
            {
                return "ExampleClass2";
            }
        }
    }

    class Program
    {
        static void Main()
        {
            ObjectActivator.AddObject("ExampleClass", typeof(ExampleClass));
            ObjectActivator.AddObject("ExampleClass2", typeof(ExampleClass2));

            IExampleClass example1 = (IExampleClass)ObjectActivator.GetInstance("ExampleClass");
            IExampleClass example2 = (IExampleClass)ObjectActivator.GetInstance("ExampleClass2");

            Console.WriteLine(example1.Name);
            Console.WriteLine(example2.Name);

            Console.ReadLine();
        }
    }
}

In the simple example above, there is an interface called IExampleClass. This interface is implemented by 2 concrete classes that we will register with the ObjectActivator, ExampleClass1 and ExampleClass2. The 2 concrete classes are then registered with the ObjectActivator.

ObjectActivator.AddObject("ExampleClass", typeof(ExampleClass));
ObjectActivator.AddObject("ExampleClass2", typeof(ExampleClass2));

Once the concrete classes are registered you can then get instances of them by using the GetInstance() method. This is what you would use in the class that you are trying to decouple. As you can see in these calls, there is no mention of the actual concrete classes. You just specify the name and then cast the result to the interface IExampleClass.

IExampleClass example1 = (IExampleClass)ObjectActivator.GetInstance("ExampleClass");
IExampleClass example2 = (IExampleClass)ObjectActivator.GetInstance("ExampleClass2");

That is all there is too it. A very simple way for managing concrete instances of classes that you want to decouple from your code to make unit testing easier withoug resorting to mocking frameworks.

When trying to tame a large legacy system, I recommend starting with constructor injection. When you start having lots of objects being passed into your constructors, then you can move on to the ObjectActivator class detailed here. I really like to keep things simple, hence why in this situation I wouldn’t jump straight into one of the more heavy weight DI frameworks.

The ObjectActivator is also a nice easy technique to use if you have a team that is inexperienced as it is quite easy to understand. The larger DI frameworks can get very confusing very quickly if left in inexperienced hands. There is no reason why you can’t jump to a framework like Castle Windsor or Unity, I just like to build up in complexity slowly. If I was working on a green field application (brand new code) then I would look more seriously a framework like Unity or Castle Windsor.

Participate with Coding in the Trenches on Facebook

Participate with Coding in the Trenches on Facebook by Click the button above.

This entry was posted in Coding and tagged , , . Bookmark the permalink.

2 Responses to Simple Dependency Injection

  1. Hugh says:

    By comparison, the IoC container I’ve written forces a single instance of each interface to encourage complete replacement of an injected dependency and minimise mistakes made by including or requesting the wrong concrete implementation. It all depends on what functionality you want, really. That in itself highlights the downfall of “One For All” frameworks, since the majority of people using it will adhere to half the rules of one paradigm and half the rules of the other, encountering only quirks and difficulties instead of “You Can’t Do That” exceptions.

  2. Pingback: All Your Mocks are Evil!! | Stephen Haunts { Coding in the Trenches }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s