Castle Windsor and Dependency Injection

Dependency Injection (DI) is the new buzz word being throw around in the tech circles.  DI has been around for a while but because of the focus on Unit Testing, DI has become more important as it is necessary to do Unit Testing.

Castle Windsor is an Inversion of Control (IoC) container that very easily allows for DI.  The site has tutorials and samples that show how to install it and use it.

Right now I am working on a project at work that I want to do complete Unit Testing so I need to install Castle Windsor first and get the Dependency Injection working.  Here is what I did to get this working.

  • First, I created a project and added the references to Castle Windsor using NuGet. Castle.Core and Castle.Windsor are the dlls that are installed.
  • Next, I added a folder called IoC and added 3 classes to it. ControllerInstaller.cs, DependenciesInstaller.cs and WindsorControllerFactory.cs.  The WindsorControllerFactory.cs highjacks the DefaultControllerFactory and adds Windsor code that will allow the DI.  The ControllerInstaller.cs class registers all the controllers automatically and the DependenciesInstaller.cs allows me to add dependencies as code is added.
  • In the Global.asax, code is added to initialize the IoC Container.

The only issue I ran into was an error thrown when the container was instantiated in the Gobal.asax file.  The code could not locate System.Web.MVC.  This code fixed that problem:

<dependentAssembly>
<assemblyIdentity name=”System.Web.Mvc” publicKeyToken=”31bf3856ad364e35″ />
<bindingRedirect oldVersion=”1.0.0.0-4.0.0.0″ newVersion=”4.0.0.0″ />
</dependentAssembly>

The next step is to add DI.