Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

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

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

Overview

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.

Implementation

Application_Start Method

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);

    // Add the following line to make sure your CustomerControllerFactory gets used
    ControllerBuilder.Current.SetControllerFactory(typeof(Acme.Web.Common.CustomControllerFactory));
    ...
}

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();
        else
            controller = null;
    }
}

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