How to create a Unity controller factory

12 03 2011

If you are using ASP.NET MVC and you want to use DI (Dependency Injection) in your application you can create a custom controller factory.

Let’s implement a custom controller factory that uses Unity as DI Container.

First we have to create a class named UnityControllerFactory. This class has to be derived from ASP.NET MVC’s built-in DefaultControllerFactory. Next we have to override the GetControllerInstance method and return a control instance by using a unity container.

//Defines a custom control factory which uses unity to get a new  controller instance.
public class UnityControllerFactory : DefaultControllerFactory
{
    //Unity container instance.
    private IUnityContainer _unityContainer;

    //Creates a new instance of UnityControllerFactory.
    public UnityControllerFactory(IUnityContainer unityContainer)
    {
        if (unityContainer == null)
        {
            throw new ArgumentException();
        }
        this._unityContainer = unityContainer;
    }

    //Retrieves a controller instance for the specified request context and controller type by using Unity.
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            return null;
        }
        return this._unityContainer.Resolve(controllerType) as IController;
    }
}

Finally we have to assign a new instance of UnityControllerFactory as  controller factory of our application’s ControllerBuilder.

UnityControllerFactory unityFactory = new UnityControllerFactory(new UnityContainer());
ControllerBuilder.Current.SetControllerFactory(unityFactory);

Below the implementation of our MVC application class.

//MVC Application
public class MvcApplication : System.Web.HttpApplication
{
    //Registeres global filters.
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    //Registers routes.
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

    //Application startup method.
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        UnityControllerFactory unityFactory = new UnityControllerFactory(new UnityContainer());
        ControllerBuilder.Current.SetControllerFactory(unityFactory);
    }
}

Our Unity controller factory implementation is completed and you can enjoy it Winking smile

Advertisements