A Guide to Inversion of control With Castle Windsor

What is Inversion of Control and what problems does it solve

Inversion of control can be described as the reversal of control in parts of a program. Another way of looking at it is a way of removing dependencies from the code you write. A good way to see what this means and how it works is to look at how we write code. If you had two classes in which one class used the other, normally there would a reference to the code in the following way:

Class A
{
    public B secondClass = new B();
}

This creates a dependency on B which could be bad since the two classes are now tightly coupled. Wikipedia defines it as object coupling that is bound at run time. So in the previous example the high coupling between the two classes could be lessened, ensuring that any changes in the Class B would not adversely affect A.

What IOC containers are there out there

I have used three different frame works but there are a few of them out there:

  1. Spring.Net
  2. Castle Windsor
  3. Autofac

Others I have not used

  1. Structure map
  2. Ninject
  3. Unity

Example of IOC using Castle Windsor.

The first step is to use nuget to install the packages in the solution:

Nuget

From There we need to add the windsor  container into global.asax in the Application_Start method:

public static IWindsorContainer Container;  //This has to be static
protected void Application_Start()
{
    //Was already here
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);

    //Added this
    ConfigureIoC();
}

private static void ConfigureIoC()
{
    Container = ContainerFactory.Create();
}

I have added a factory to setup the container:

public static class ContainerFactory
{
    private static IWindsorContainer Container { get; set; }

    public static IWindsorContainer Create()
    {
        Container = new WindsorContainer();
        Container.Install(FromAssembly.This());
        ConfigureControllers();
        return Container;
    }

    private static void ConfigureControllers()
    {
        var controllerFactory = new WindsorControllerFactory(Container.Kernel);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }
}

Once you have configured the factory all you need to do is configure what we call the installers.  You can do this in one file but we have separated them.  Here is an example of some of the installers:

The first one is to configure all of our services:

public class ServiceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
                  AllTypes.FromAssemblyNamed("Assembly.Project.Service")
                 .Where(Component.IsInNamespace("Assembly.Project.Service.Services"))
                 .WithService.DefaultInterfaces()
                 .Configure(c => c.LifestyleTransient()));
    }
}

The next one will configure all of our controllers:

public class ControllersInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
       container.Register(AllTypes.FromThisAssembly()
                .BasedOn<IController>()
                .If(t => t.Name.EndsWith("Controller"))
                .Configure(c => c.LifestyleTransient()));
    }
}

The last part is to write the controller with the properties you need.   I have used constructor injection in this example, so all properties that will be injected via the constructor:

namespace Namespace.Web.Controllers
{
    public class HomeController : Controller
    {
        private IService _service;
        public HomeController(IService service)
        {
            _service = service;
        }

        [HttpGet]
        public ActionResult Index()
        {
            Model model = _service.DoSomeThing();
            return View(model);
        }
    }
}

 

This should help with configuring your solution with castle.   Hope it has been helpful.



Sharing constants between C# and javascript

I found this on Stack Overflow and I thought it was awesome so check it out:

http://stackoverflow.com/a/6217109/343088

Enjoy!



Error upgrading from MVC 3 to MVC4

We recently upgraded one of our applications from MVC 3 to MVC 4. In development we use the Visual studio development server and the upgrade seemed fine. When we deployed the files to our staging environment we had the following error:



This seemed happen only when we navigated to an area. After much gnashing of teeth we found that the web.config in each View folder was still referencing the version 3:

<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" namespace="System.Web.Mvc" tagPrefix="mvc" />

To Fix this, just update the version.



DatePicker with dynamic DOM Elements

I have been battling with a problem with the date picker. The problem is that when I add new inputs with the DatePicker class they do not behave in the same way as with the document load. The code I was using was:

$(document).ready(function (){
     $("input.datePicker").datepicker();
});

After that I was just trying to rebind the events using the destroy and datepicker methods.  Unfortunately this did not work!  Eventually I found this great stackoverflow answer and since I was cloning the elemtns I had to remove the hasDatePicker to rebind.

$('.date').last().removeClass('hasDatepicker');
$('.date').last().removeAttr('id');
$('.date').last().datepicker();



Hopefully this helps if you have the same problem.



Test Driven Design By Example

We have started using Test Driven Design (hopefully properly) over the last few months and I wanted to share our experiences of it. Before we started using TDD our approach to unit testing was to find a unit of work that we had just completed and write a test to make sure the output of the method was what we expected. The most obvious problem with this is that while we are hoping that the unit test will be testing the method, actually what we were doing was testing the method and everything that used it. So in this case we were testing any service calls, database calls, any other classes and objects that are used in the method.

Looking at how TDD works

The easiest way of understanding what test driven design is, can be achieved by looking at the following diagram: Test-driven development
Please note I have obtained this image from Wikipedia (the article can be found here) To summarize:

  1. Before writing any code to solve the issue:  write a test to test the functionality.  If the test passes then the functionality exists or the test has not been written correctly.
  2. Run the tests to make sure that this does fail.
  3. Write only enough code to make the test pass.
  4. Run all the tests to make sure that the test passes.   All the tests should be run to make sure that the new code does not break the existing tests.
  5. Refactor and clean up the code.

The Role of mocks and stubs

To understand what a mock object is, it is a good idea to see what they do in the context of a unit test.  I have said previously that a bad test is a test that unwittingly tests the objects that the unit of work uses, so databases external classes etc.  A good way of only testing the code in the method would be to create fake objects that return what you expect it to.  This eliminates their influence on the logic by limiting the external factors.  I found a really good answer on stackoverflow on what the difference is between a mock and a stub: answer.

Bad unit test designs

From what I have seen a lot of tests that have been written in the past are integration tests.  An integration test is a test that tests the integration (I know it is obvious, but I still thought I would make it clear) of the system to another system, most often this is used to test the integration of the application being tested and a database.  I am not saying integration tests are a bad thing, what I am saying is that integration tests masquerading as unit tests are a bad thing.  The reason for this is that a unit test should test the small unit of work that the code handles and not the external factors on the method.  These tests make it hard to understand what is being tested and what is not.  The other issue is that they are extremely brittle:  since they rely heavily on external factors, if any of the objects change the test will break.

Benefits of Test Driven Design

  • When you write a test to describe the way a unit of work should work,  it helps you only write code to make the test pass, therefor making sure that there is no creep.
  • With adding of unit tests, the code should be more stable and less prone to bugs.
    • This can be shown by research done by Microsoft entitled Realizing quality improvement through test driven development: results and experiences of four industrial teams.  An except from the conclusion of this paper: “Our experiences and distilled lessons learned, all point to the fact that TDD seems to be applicable in various domains and can significantly reduce the defect density of developed software without significant productivity reduction of the development team. Additionally, since an important aspect of TDD is the creation of test assets—unit, functional, and integration tests. Future releases of these products, as they continue using TDD, will also experience low defect densities due to the use of these test assets”.  This paper can be found at: http://research.microsoft.com/en-us/groups/ese/nagappan_tdd.pdf
  • By using continuous integration and running unit tests when code changes are made, the unit tests can make sure that the changes are not damaging existing functionality.
  • Unit tests can often show that a method or a class has too much responsibility.  This can be seen if it is not clear what the output of a method is or if there is a too many inputs or if a lot is changed inside the method.   Unit test help the developer to think about how the code they are about to write will pass the test and only the test.

Example Of Test Driven Design

In this example I am going to create a Fibonacci Sequence.  To start off I created a project and a test project.

These are the steps I used in my TDD:

In the Test project I created a class called FibonacciSequenceTests.  In the class I created the following test:

public void Test_Find_Fibonacci_Sequence_At_Position_Correct()
{
     //Arrange
     FibonacciSequence fibonacciSequence = new FibonacciSequence();

     //Act
     int sequenceAtPosition = fibonacciSequence.FindFibonacciSequenceAtPosition(8);

     //Assert
     Assert.AreEqual(sequenceAtPosition, 21);
}

This obviously failed since there is no functionality in the solution, so I created the class:

public class FibonacciSequence
{
     public int FindFibonacciSequenceAtPosition(int n)
     {
          int a = 0;
          int b = 1;

          // In N steps compute Fibonacci sequence iteratively.
          for (int i = 0; i < n; i++)
          {
               int temp = a;
               a = b;
               b = temp + b;
          }
          return a;
     }
}



kick it on DotNetKicks.com