What the hell is Inversion of Control and why should I care?

I have been trying to deepen my understanding of IoC (Inversion of Control) or “Dependency Injection” as Martin Fowler prefers.

For the first time I heard a really good explanation of what IoC is and why it is useful. This was during a podcast with Scott Hanselmann whilst he was discussing MVCTurbine in his Hanselmiutes podcast.

Scott described the process of creating a new MVC app: After you have fired up Visual Studio and clicked file > new > MVC project you must then go about the business of creating a controller. Once that is done you need to create a view and then you can fire up your app and see a web page. Now you need to start adding some infrastructure to your controller to give it the ability do things like logging. At this point you need to make a decision about where the responsibility or ‘control’ will be placed for getting the logging implementation. Now logging is a great example, nearly all applications need to log information so it is likely that you will be making use of an existing library, it is also likely that logging is going to be performed by most handlers. If you opt to make it the responsibility of the controller to locate and instantiate your logging library then all controllers will need the code that does this. If instead you opt to invert the control of this location and
instatiation then you need a mechanism to do this… enter Dependency Injection. Instead of adding code to your controller that locates and instantiates a logger you place a dependancy into your controller on an interface that describes the interraction with your logger. Then you pick a container like Autofac or Windsor and configure it so that at runtime it knows how to instantiate the implementation that you want to use for logging.

With IoC when you look at the code of the controller class all you see is a public property of the logger interface type:

public ILog Logger{ get; set; }

Unless you first understand that the dependancy will be injected at runtime the code looks a bit weird and like it couldn’t possibly work because it is not obvious how the implementation will be located and instantiated. When your application starts you must add some code that configures your chosen IoC container so that it knows how to inject the logging implementation into your MVC controller at runtime.