Jasinski Technical Wiki


Home Page
All Pages

Quick Search
Advanced Search »

Contributor Links

Create a new Page
File Management
Your Profile

Other Wiki Sections



Custom Controller Factory - Putting Controllers in an External Assembly - ASP.NET MVC

Modified on Tue, Sep 18, 2012, 3:27 PM by Administrator Categorized as ASP·NET MVC


In the interest of building a modular design to facilitate deployment, we would like to have each module of code in its own assembly. In a WebForms project, this is simply a matter of moving the ASPX code-behind files and related code files. With an MVC project, you need to take the additional step of implementing a custom controller factory. This article explains how.


Application_Start Method

protected void Application_Start()

    // Add the following line to make sure your CustomerControllerFactory gets used

Reusable Code

The following class can go in your web project.

public class CustomControllerFactory : IControllerFactory
    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        if (string.IsNullOrEmpty(controllerName))
            throw new ArgumentNullException("controllerName");

        IController controller;

        string cTypeName = "Acme.Web.Controllers." + controllerName + "Controller";

        var cType = Type.GetType(cTypeName);

        if (cType != null)
            controller = Activator.CreateInstance(cType) as IController;
            return controller;

        var assemblyPath = requestContext.HttpContext.Server.MapPath("~");

        // For simplicity sake, we hard code the name of the assembly, but you can 
        // implement whatever logic you want here, possibly pulling from a configuration file.
        assemblyPath = Path.Combine(assemblyPath, @"bin\MyControllers.DLL");

        var assembly = Assembly.LoadFrom(assemblyPath);

        var c = assembly.CreateInstance(cTypeName);

        controller = c as IController;

        return controller;

    public void ReleaseController(IController controller)
        if (controller is IDisposable)
            (controller as IDisposable).Dispose();
            controller = null;

ScrewTurn Wiki version Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2023, Patrick Jasinski.