Posts Tagged ‘Inversion Of Control’

Inversion of Control and StructureMap: Part 1

Tuesday, November 10th, 2009

I’ve been asked at work to provide some documentation to the other guys on the team around Inversion of Control and how we should be using StructureMap on our projects. Nothing in these upcoming blogs is revolutionary or new and there is nothing that you couldn’t from countless other sources but I thought I would share it anyway. I hope its of use.

What is StructureMap?

StructureMap is an Inversion Of Control container. There are a few out there but essentially they all do the same thing:

  • StructureMap
  • Windsor Castle
  • Spring.Net
  • AutoFac
  • Unity
  • Ninject

Before we delve too much into the specifics of StructureMap I thought we should start with a little refresher course on Dependency injection and Inversion of Control.

What is Inversion Of Control?

Consider the following code:


class Class1
{
   public void SomeMethod()
   {
      var class2 = new Class2();

      class2.SomeOtherMethod();
   }
}

Class1 is always (tightly) coupled to Class2. Even if we wrap Class2 with an interface we are still coupled to the concrete implementation of Class2. Because Class1 creates our implementation of IClass2


class Class1
{
   public void SomeMethod()
  {
     IClass2 class2 = new Class2();

     class2.SomeOtherMethod();
  }
}

How do we get around this coupling? If Class1 doesn’t create Class2 but is given an instance of an object that is already created using its interface then Class1 will no longer be coupled to Class2.

We can pass into Class1 whatever implementation of IClass2 we want it could be the real implementation of Class2 or it could be a mock object. It can be anything we want it to be we have total freedom now.

When a class no longer creates the dependant classes it requires to do its work but is given them this is called dependency injection. We can do this in two ways using either the  Constructor or using properties.

In general constructor injection is the preferred approach, although there are times when you will need to use property injection. Class1 below has been refactored so that we now use constructor injection.


class Class1
{
   private readonly IClass2 _class2;

   public Class1(IClass2 class2)
   {
      _class2 = class2;
   }

   public void SomeMethod()
   {
      _class2.SomeOtherMethod();
   }
}

Poor Man’s Dependency Injection

So if we don’t create our dependencies in our classes anymore where do we create them? One solution is to use what is known as poor man’s dependency injection (PMDI), which is a technique where we incorporate two constructors on our class. One that injects our dependencies in through the constructor and a default constructor that creates the concrete implementations of our dependencies for us.

In our normal code we would use the default constructor but in our tests we would inject our mocks in through the testing constructor. See our refactored Class1 with that uses poor man’s dependency injection implemented.


// Testing Constructor – our dependencies can be
// injected using this constructor.
public Class1(IClass2 class2)
{
   _class2 = class2;
}

// Default Constructor – Our dependencies are created
// using this constructor.
public Class1():this(new Class2())
{
}

PMDI is great for implementing inversion of control for legacy code as it provides you with a way to decouple your code and test whilst limiting the extent of your refactoring because you are keeping your existing (default) constructor and hence are not breaking any existing code that depends on that class.

Why Don’t We Use Poor Man’s Dependency Injection All The Time?

Poor man’s dependency injection work’s ok, on smaller projects and as I said with legacy code. However what you find is that on larger projects with complex dependency graphs things can get out of control pretty fast and things can start hurting.

Consider the following scenario: ClassA has a dependency on ClassB, which in turn has a dependency on ClassC which in turn has a dependency on ClassD… ok you get the idea..All of a sudden the constructor for ClassA looks like this:

class ClassA
{
   public ClassA():this(new ClassB(new ClassC(new ClassD(new ClassE()))))   {}

   public ClassA(IClassB classB){}
}

Pretty ugly isn’t it. all the other classes would have equally nasty and complex constructors also. Now consider what would happen if I changed the signature of ClassE so that it now took an connection string.  This would mean that I would have to change the constructors on Classes A, B, C and D. Now all of a sudden dependency injection doesn’t seem like such a great idea and you want to strangle the guy that first ever suggested using it…and remember this is only for a trivial example.

IOC Container To The Rescue

An IOC container such as StructureMap handles these complexities and does all the heavy lifting for you.

The container knows about your interfaces and the concrete classes that implement those interfaces. It knows how to instantiate your objects in your domain and resolve their dependencies for you. It doesn’t matter how complex the dependency graph is any more because your IOC container will do it all for you. Once you start delving into IOC containers you realize that they can do loads of other cool things too but I’ll save that for later..