Skip navigation

Control the Controller

In ASP.NET MVC, a Controller Processes the Request ... but Who Controls the Controller?





Control the Controller

In ASP.NET MVC, a Controller Processes the Request ... but Who Controls the Controller?


By Dino Esposito


Classic ASP.NET and ASP.NET MVC (now in beta) are two sides of the same coin, as both let you build Web applications for the .NET platform. In doing so, both platforms provide you with some facilities to output HTML and process incoming HTTP requests. A key difference between the platforms, though, is in how you write the code that services an individual request. In classic ASP.NET, the request processing is delegated to an HTTP handler. An HTTP handler can be as simple as a class that exposes a ProcessRequest method. The method then will write its response directly to the output stream. More likely, the HTTP handler is as sophisticated as the System.Web.UI.Page class. In this case, the request goes through a number of stages and the response comes out of the markup generated by a bunch of constituent server controls.


On the other hand, the ASP.NET MVC Framework introduces the idea that each incoming HTTP request is being serviced through the execution of a method on a controller class. In doing so, the ASP.NET MVC paradigm splits the responsibility of the ASP.NET s Page HTTP handler across multiple components primarily, the routing system, the controller, and the view.


Whenever a new request hits the front-end of an ASP.NET MVC application, the routing system selects the right controller, gets an instance of the class, and invokes the proper method on it. Nicely enough, the small piece of logic that takes care of creating an instance of the right controller has been abstracted to an interface: the IControllerFactory interface. Among other things, this means you can write and register your own controller factory, thus gaining full control over the process of initialization and instantiation of the controller.


In this article, I ll go through the details of custom controller factories while paying special attention to the actual benefits that custom controller factories bring to developers.


The Controller Factory

Each request that an ASP.NET MVC application originates is actually managed by a special HTTP handler that is a part of the framework: the System.Web.Mvc.MvcHandler class. The following code executes from the ProcessRequest method of the MVC HTTP handler:


IControllerFactory factory =



The GetControllerFactory method determines which factory object will be used to create an instance of the controller class referenced in the URL of the request being processed. A controller factory is a class that implements the IControllerFactory interface, listed here:


public interface IControllerFactory


 IController CreateController(RequestContext requestContext,

  string controllerName);

 void ReleaseController(IController controller);



To create your own controller factory, you simply come up with a class that implements IControllerFactory or, better yet, you derive a new class from the default implementation of the IControllerFactory interface, as shown here:


public class MyControllerFactory : DefaultControllerFactory


 public MyControllerFactory(...)




 protected override Icontroller

   GetControllerInstance(Type controllerType)






At the end of the day, DefaultControllerFactory saves you from writing a bunch of boilerplate code exposing through the virtual method GetControllerInstance just the behavior you might want to customize the creation of an instance of the specified controller type. Passing through the DefaultControllerFactory base class is only a form of convenience; implement the IControllerFactory interface directly if that helps you feel more in control of things.


Why a Custom Controller Factory?

An old proverb reminds us that you should not be doing something only because it is doable. So what s the driving force for custom controller factories in ASP.NET MVC? The primary reason for having a custom controller factory is making available more information to actual controllers in a more flexible way. Also, through a custom factory, you can implement your own policies for pooling and caching, and you can save some CPU cycle not getting new instances for each and every request. In other words, a custom controller factory gets you more control over the most critical phase in the lifetime of a request within ASP.NET MVC applications.


As a developer, you are responsible for writing all controller classes and managing all of the required source code. If you need to initialize the controller in a special way, or if you need it to retrieve some special pieces of information, you easily can code your way to it. You can modify the constructor of the controller and place there any sort of special initialization you need. Here s an example:


public class HomeController : Controller


 public HomeController()






In this way, though, you can t add any extra argument to the constructor for the simple reason that you can t control the code that actually invokes the controller s constructor (the controller factory).


You need a controller factory to optimize the management of controller instances via pooling and caching. You also need a controller factory to simplify and empower the way in which additional data is injected into the controllers. In this regard, dependency injection (DI) frameworks can provide some help.


Dependency Injection Containers

As discussed in the November 2008 installment of CoreCoder, a DI framework is a library aptly designed to resolve class dependencies in the most flexible way. The framework is based on a static or dynamic list of mappings between types. From the framework perspective, resolving a dependency means getting an input type and returning an instance of an output type. Most of the time, type mappings are declaratively defined in a configuration file.


Several popular DI frameworks exist, including Spring.NET, StructureMap, and Castle Windsor. In this article, I ll use Microsoft Unity from the latest release of Enterprise Library 4.1 (see


What s the ultimate benefit of having a DI container integrated in a controller factory? With a DI framework aboard, you don t need to edit the source code to bring new or different data in the controller. All you need to do is modify the mapping, which is information you might have stored in a configuration file. You don t need to edit and maintain the constructor of any controller. Instead, you simply define as dependencies parameters in the constructor of the controller, or public properties. The framework will automatically resolve those dependencies for you.


As an example, let s see how to integrate Microsoft Unity in all controllers of a sample ASP.NET MVC application. (The code has been tested under ASP.NET MVC Beta and Enterprise Library 4.1, but you should not experience troubles with other versions.)


Building Your Own Controller Factory

A custom controller factory must be linked to the ASP.NET MVC application as early as possible and precisely in the Application_Start global event handler. Here s a possible way to rewrite the sample handler that the Visual Studio 2008 project template gets you:


protected void Application_Start()


   // Usual stuff


   // Register the controller factory




The full source code of RegisterCustomControllerFactory is shown in Figure 1. As you can see, the method gets an instance of the UnityContainer class (the DI container for the Unity library) and makes it work based on the mappings in the unity section of the configuration file (see Figure 2). After that, an instance of the custom controller factory class is passed on to the ASP.NET MVC Framework s controller builder. In Figure 1, the Unity container also is exposed for further use through a public property named IocContainer.


public class MvcApplication : System.Web.HttpApplication


 // Local member

 private static UnityContainer _iocContainer;

 // Public reference to the DI container

 public static IUnityContainer IocContainer


   get { return _iocContainer; }


 // Register a custom controller factory for the MVC application.

 private static void RegisterCustomControllerFactory()


   if (_iocContainer == null)


      UnityConfigurationSection section;

      section = ConfigurationManager.GetSection("unity")

        as UnityConfigurationSection;

      _iocContainer = new UnityContainer();



   IControllerFactory factory = new SampleControllerFactory(_iocContainer);



 // Rest of boilerplate code



Figure 1: Registering a custom controller factory.




   <section name="unity"


    Microsoft.Practices.Unity.Configuration />






      <type type="Samples.Mvc.IDataFinder, myAPI"

                mapTo="Samples.Mvc.NWindFinder, finder" />






Figure 2: Static mappings for the Unity container.


Figure 3 shows the source code of the sample factory class. The constructor simply gets the reference to the DI container and stores it internally. The overridden GetControllerInstance method simply tells the DI container to resolve any dependency related to the controller type (that s the trick). This code is apparently simple and not particularly capable; instead, it demonstrates the full power of modern DI frameworks.


public class SampleControllerFactory : DefaultControllerFactory


 private readonly IUnityContainer _iocContainer;

 public SampleControllerFactory(IUnityContainer container)


   this._iocContainer = container;


 protected override IController GetControllerInstance(Type controllerType)


   if (controllerType == null)

     throw new ArgumentException();

   return _iocContainer.Resolve(controllerType) as IController;



Figure 3: The SampleControllerFactory class.


The Resolve method attempts to return an instance of a type that is mapped to the controller type. It looks in the configuration file (as mentioned, in fact, we used static design-time mapping) and finds no dependencies. Hence, it simply takes on the controller s default constructor and gets an instance to return. However, the DI framework also can do a number of interesting things, such as resolving dependencies inside the controller s class.


Adding Dependencies to Controllers

Let s suppose you have a controller class with a public property that references an external component. Here s some sample code:


public class HomeController : Controller



 public IDataFinder DataFinder { get; set; }




In the Unity section of the configuration file, you also add a mapping between IDataFinder and a concrete type that implements the interface:


<type type="Samples.Mvc.IDataFinder, FinderApi,

 Version=" mapTo="Samples.Mvc.NWindFinder,

 Finder, Version="/>


To populate the DataFinder property with an instance of the mapped type NWindFinder, you would normally need to invoke Resolve directly on a container s instance. The nice thing about most DI containers, though, is that you can get this behavior for free, simply by decorating the property with the Dependency attribute.


While resolving dependencies on the controller type, DI containers go further and look for constructor parameters, base types, and public properties. If they find a dependency on a property, as in this example, they automatically resolve it. What does it mean to you? The DataFinder property is auto-magically set to an instance of the type as mapped in the configuration file. And you can change this dependency in a declarative manner. And you can add new dependencies simply by adding a new public property to the controller class and a line in the configuration file. All in all, it s not an entirely new set of capabilities, but a more powerful way of dealing with class dependencies.


Similarly, the DI container can resolve parameters in the controller s constructor, as shown here:


public HomeController([Dependency] IDataFinder finder)


    DataFinder = finder;



Given this code, and proper mappings, the Unity DI container will be able to figure out which dependencies the constructor has on parameters and resolve them properly. In this case, modifying the constructor of the controller only takes a few moments and has no risk of introducing bugs.



When using a DI-powered controller factory, you can declare additional properties (or the constructor s parameters) in actual controllers and have the DI framework provide for run time values. You never deal with instantiation and initialization and simply think in terms of interfaces.


When do you really need a custom factory for controllers? Well, on average, ASP.NET MVC controllers are simple classes that are given by an ensemble of public one-off methods. If you need to create some sort of state around these methods and inject external data and capabilities, the best way is by using a DI framework. At that point, integrating the DI container directly in the controller s factory is the choice that gives the best cost/benefit ratio.


Source code accompanying this article is available for download.


Dino Esposito is an architect at IDesign and specializes mainly in ASP.NET, AJAX, and RIA solutions. Dino is the author of Microsoft .NET: Architecting Applications for the Enterprise (Microsoft Press, 2008). He also wrote Programming ASP.NET 3.5 Core Reference, also for Microsoft Press. Late-breaking news is available at




Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.