Custom IoC Container for Dependency Injection with an Asp.Net Mvc website usage example

I’ve recently been working on some mvc helper controls and wanted to use TDD for both aiding the design and having a test harness for the future.

In order to aid the use of tdd and improve the overall design I wanted to utilise dependency injection.

There are loads of good IoC containers out there which include facilities for dependency injection for example Structure Map (really like this one), Spring.Net (I use this at my real job), Castle Windsor etc. etc to name but a few.

For my controls I wanted a container that was extremely lightweight and fast so I decided it would be really interesting to have a go at rolling my own, I know it’s re-inventing the wheel slightly but I’m a great believer in the worth of knowing how things are done (I imagine most of us in this trade are the same in that regard).

Anyway, I’ve really enjoyed building this and would welcome anyone trying it out – hopefully people will find it both powerful and really easy to use (I’ve tried to make the syntax really intuitive and fluent).

I’ve named it RapidIoc (I do plan to add some extra facilities over time to beef it up a little – probably some AOP support).

Download

RapidIoc Binary

RapidIoc Source Code

RapidIoc Tests

RapidIoc Mvc Web Site Example

Overview

The dll stands at 20.5KB (nice and small).

The key features include:

  • Automatic and manual wiring
  • Constructor injection
  • Property injection
  • Fluent interface for object registration
  • Supports per-request, singleton and http context object resolving (http context resolving will only work in web apps)
  • Automatic wiring can be overridden

Setup

Setting up the container is really simple – you just need to add a reference to the dll.

There aren’t any handlers of configurations as it’s all handled within the dll.

Tutorial

As a lot of people are starting to use dependency injection with the ASP.Net MVC framework, I’ve decided to do a little tutorial on hooking it up with a basic MVC app (included in the download.)

Step 1 – Add a reference

So, first thing to do is create a new Asp.Net Mvc application and add a reference to the RapidIoc.dll.

Step 2 – Create a controller factory

Set up a controller factory to hand over creating the controllers to the RapidIoc container.

Create a class similar to the following:

  1. using System;
  2. using System.Web.Mvc;
  3. using RapidIoc;
  4. namespace RapidIocTestSite
  5. {
  6.     public class RapidIocControllerFactory : DefaultControllerFactory
  7.     {
  8.         protected override IController GetControllerInstance(Type controllerType)
  9.         {
  10.             if (controllerType == null)
  11.             {
  12.                 return null;
  13.             }
  14.  
  15.             IController controller = (IController)IocContainer.TryResolve(controllerType);
  16.             if (controller != null)
  17.             {
  18.                 return controller;
  19.             }
  20.             else
  21.             {
  22.                 return base.GetControllerInstance(controllerType);
  23.             }
  24.         }
  25.     }
  26. }

In the Global.asax file, add the following line to the Application_Start method:

  1.         protected void Application_Start()
  2.         {
  3.             RegisterRoutes(RouteTable.Routes);
  4.  
  5.             ControllerBuilder.Current.SetControllerFactory(typeof(RapidIocControllerFactory));
  6.         }

That concludes the setup for the RapidIoc container, nice and simple.

Step 3 – Create your objects

This will be a bit of a contrived example but it will demonstrate a good number of features of the container.

Create the following models:

  1.     public interface ICustomer
  2.     {
  3.         string FirstName { get; set; }
  4.         IContact ContactDetails { get; set; }
  5.     }

  1.     public class Customer : ICustomer
  2.     {
  3.         public string FirstName { get; set; }
  4.         public IContact ContactDetails { get; set; }
  5.     }

  1.     public interface IContact
  2.     {
  3.         string TelephoneNumber { get; set; }
  4.         IAddress CustomerAddress { get; set; }
  5.     }

  1.     public class Contact : IContact
  2.     {
  3.         public string TelephoneNumber { get; set; }
  4.         public IAddress CustomerAddress { get; set; }
  5.     }

  1.     public interface IAddress
  2.     {
  3.         int HouseNumber { get; set; }
  4.         string PostCode { get; set; }
  5.     }

  1.     public class Address : IAddress
  2.     {
  3.         public int HouseNumber { get; private set; }
  4.         public string PostCode { get; private set; }
  5.  
  6.         public Address() { }
  7.  
  8.         public Address(int houseNumber, string postCode)
  9.         {
  10.             this.HouseNumber = houseNumber;
  11.             this.PostCode = postCode;
  12.         }
  13.     }

Next thing to do is add a property to the HomeController: this will be the property that we’re going to inject.

Also set the ViewData.Model to the property as we are going to use that later in the view.

For example, your home controller should look something like the following:

  1.     public class HomeController : Controller
  2.     {
  3.         /// <summary>
  4.         /// This is the prpoerty we're going to inject via the Ioc Container.
  5.         /// </summary>
  6.         /// <value>The customer.</value>
  7.         public ICustomer Customer { get; set; }
  8.  
  9.         public ActionResult Index()
  10.         {
  11.             this.ViewData.Model = this.Customer;
  12.             return View();
  13.         }
  14.     }

Step 4 – Register your objects

This is the last step in setting up the application for injection as the object resolution is handled within the controller factory you set up in step 1.

Firstly create a class similar to the following:

  1. using RapidIoc;
  2. namespace RapidIocTestSite
  3. {
  4.     /// <summary>
  5.     /// Ioc Registration.
  6.     /// </summary>
  7.     public class IocRegistration
  8.     {
  9.         public void Register()
  10.         {
  11.  
  12.         }
  13.     }
  14. }

Then call the Register method from the application start method in the Global.asax:

  1.         protected void Application_Start()
  2.         {
  3.             RegisterRoutes(RouteTable.Routes);
  4.  
  5.             ControllerBuilder.Current.SetControllerFactory(typeof(RapidIocControllerFactory));
  6.  
  7.             IocRegistration iocRegistration = new IocRegistration();
  8.             iocRegistration.Register();
  9.  
  10.         }

There are two ways to use the container to inject your properties: Automatically and manually. (Note: automatic wiring does not work when using complex types for constructor injection – only property injection).

You can use either or a combination of these ways to register your objects.

Automatic Wiring Example

When using automatic wiring, the IocContainer inspects each class in the hierarchy (from the HomeController in this case) and checks if a registered object exists for each property interface type, if a registered object exists for a property it is injected.

For example, if you registered multiple controllers with an ICustomer property, they would all be automatically populated with the Customer instance. The Customer class IAddress property would then be automatically injected with the Address class and so on.

  1.     /// <summary>
  2.     /// Ioc Registration.
  3.     /// </summary>
  4.     public class IocRegistration
  5.     {
  6.         public void Register()
  7.         {
  8.             #region Controllers
  9.  
  10.             IocContainer.Register<HomeController, HomeController>
  11.                 (
  12.                     Wiring.Manual,
  13.                     Scope.Request
  14.                 );
  15.  
  16.             #endregion
  17.  
  18.             #region Customers
  19.  
  20.             IocContainer.Register<ICustomer, Customer>
  21.                 (
  22.                     Wiring.Automatic,
  23.                     Scope.Request,
  24.                     Properties.Configure()
  25.                         .Inject<ICustomer>(x => x.FirstName, "Sean")
  26.                 )
  27.                 .Register<IContact, Contact>
  28.                 (
  29.                     Wiring.Automatic,
  30.                     Scope.Request,
  31.                     Properties.Configure()
  32.                         .Inject<IContact>(x => x.TelephoneNumber, "12345 678910")
  33.                 )
  34.                 .Register<IAddress, Address>
  35.                 (
  36.                     Wiring.Automatic,
  37.                     Scope.Request,
  38.                     ConstructorParameters.Configure()
  39.                         .Inject(123)
  40.                         .Inject("SW10 5ZZ")
  41.                 );
  42.  
  43.             #endregion
  44.         }
  45.     }

 

Manual Wiring Example

Manual wiring involves explicitly setting each property or constructor for injection. Any manually wired injection will override any automatically wired injection.

  1. public void Register()
  2.         {
  3.             #region Controllers
  4.  
  5.             IocContainer.Register<HomeController, HomeController>
  6.                 (
  7.                     Wiring.Manual,
  8.                     Scope.Request,
  9.                     Properties.Configure()
  10.                         .Inject<HomeController>(x => x.Customer, Resolve.Object<ICustomer, Customer>())
  11.                 );
  12.  
  13.             #endregion
  14.  
  15.             #region Customers
  16.  
  17.             IocContainer.Register<ICustomer, Customer>
  18.                 (
  19.                     Wiring.Manual,
  20.                     Scope.Request,
  21.                     Properties.Configure()
  22.                         .Inject<ICustomer>(x => x.FirstName, "Sean")
  23.                         .Inject<ICustomer>(x => x.ContactDetails, Resolve.Object<IContact, Contact>())
  24.                 )
  25.                 .Register<IContact, Contact>
  26.                 (
  27.                     Wiring.Manual,
  28.                     Scope.Request,
  29.                     Properties.Configure()
  30.                         .Inject<IContact>(x => x.TelephoneNumber, "12345 678910")
  31.                         .Inject<IContact>(x => x.CustomerAddress, Resolve.Object<IAddress, Address>())
  32.                 )
  33.                 .Register<IAddress, Address>
  34.                 (
  35.                     Wiring.Manual,
  36.                     Scope.Request,
  37.                     ConstructorParameters.Configure()
  38.                         .Inject(123)
  39.                         .Inject("SW10 5ZZ")
  40.                 );
  41.  
  42.             #endregion
  43.         }

Note: when using Resolve.Object<TTypeToResolve, TConcrete> to inject a property or constructor parameter it creates a new instance of the generic parameter TConcrete type passed in. It then checks to see if a registered object exists with the same TTypeToResolve and TConcrete, if one exists it will be injected from the registered objects collection. Basically what this means is if you call Resolve.Object on an object that is not registered, it will create a default instance of the concrete type and inject that.

Scope

In the above example I’ve set everything to Request scope.

Other scopes available are singleton and http context. I imagine it’s fairly obvious what they do but for example, if your controller has a Repository property that should be treated as a singleton, you just set the scope to Singleton.

View

To prove that it is working, add the following to the Home Index view and you should see the data you injected printed out.

  1.     <% if (this.Model != null)
  2.        { %>
  3.        <strong>Customer</strong><br />
  4.        Firstname : <%= this.Model.FirstName %><br />
  5.        <strong>Contact Details</strong><br />
  6.        Telephone: <%= this.Model.ContactDetails.TelephoneNumber %><br />
  7.        <strong>Address</strong><br />
  8.        House number: <%= this.Model.ContactDetails.CustomerAddress.HouseNumber %><br />
  9.        Post code: <%= this.Model.ContactDetails.CustomerAddress.PostCode %>       
  10.     <% } %>

Overloads

There are various overloads which should be useful, I’ve commented all the public methods so hopefully it should be fairly easy to use.

Conclusion

So to conclude, it has been a really enjoyable experience building a container instead of just consuming one of the usual frameworks, I would recommend everyone re-inventing the wheel every now and then.

If anyone tries it out, I’d love to hear how you get on, from my initial tests it seems to work really well (but I am probably fairly biased).

If anyone thinks it’s a good approach and would be worth turning into a real project, let me know and I could possibly look at starting an open source project.

Kind Regards,

Sean McAlinden

www.asp-net-mvc.com

2 Comments

Comments have been disabled for this content.