Click here to Skip to main content
Click here to Skip to main content

Understanding and Extending Controller Factory in MVC

, 24 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This tip is all about understanding the controller factory and exploring it...

Introduction

In ASP.NET, MVC controller lies between model and view, this means the controller is responsible for communicating with model and displaying view accordingly.

Background

When request reaches the ASP.NET MVC application, routing system handles it and forwards it to controller factory. Now here the role comes of the Controller Factory. Controller factory is responsible for handling the incoming request and mapping it to specific controller.

Here is how it works:

 Request  --> Routing System ---> Controller Factory ---> Invoke Controller   

In this figure, I tried to explain where the role exists of controller factory.

Existing Controller Factory

By default, ASP.NET MVC uses DefaultControllerFactory class for creating controller after receiving request from Route Handler.

DefaultControllerFactory is implemented from IControllerFactory interface which has two important methods:

  1. CreateController: This method takes 2 parameters, RequestContext and controller name as string.  
  2. ReleaseController: Get instance of controller and release it.

It also contain GetControllerSessionBehavior method for session related tasks.

You might experience that when we add a new controller in MVC application, the Controller class always ends with Controller suffix. There are certain constraints we must follow while working with controller in MVC.

Example

Our controller class must have constructor with no parameter. All the actions in controller class must be public and class must not be abstract…. etc.

These are the default naming conventions which have been used by Microsoft for MVC Framework.

The controller class we use in our MVC application is derived from Controller (abstract) class which implements ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter and IResultFilter.

With the help of the above mentioned interfaces and ControllerBase class, the Controller class helps to create a controller easily.

Why Stick with Existing Controller Factory?

When you will try to develop an application with ASP.NET MVC, you must follow the pattern and convention defined by Microsoft.

Sometimes, our organization's design principle doesn’t allow to use these default conventions instead, we use our own. So what next??

Fortunately, MVC provides well separation of concern so we can override existing controller factory to implement our own.

Please note: I would not suggest the readers to completely override existing controller factory unless and until you really need it.

Create and Implement Custom Controller Factory

As I mentioned earlier for defining controller factory, we must use IControllerFactory which has 2 important methods.

I have tried to explain the work of custom controller factory with a few lines of code just for keeping things simple and short.

Below is the example in which I have created a Custom_Controller_Factory class for demonstrating the work of Controller Factory.

public class My_Controller_Factory : DefaultControllerFactory 
    {
        public override IController CreateController
        (System.Web.Routing.RequestContext requestContext, string controllerName)         {
            string controllername = requestContext.RouteData.Values
            ["controller"].ToString();           
            // Debug.WriteLine(string.Format("Controller Name : {0}", controllername));            
             Type controllerType = Type.GetType(string.Format
            // (/*need to set full qualifiere name*/"Custom_Controller_Factory.Controllers.{0}",controllername));
            // typeof(Home);            
            IController controller = Activator.CreateInstance(controllerType) as IController;            
            return controller;         
    }
        public override void ReleaseController(IController controller)        {
            IDisposable dispose = controller as IDisposable;            if (dispose != null)            {
                dispose.Dispose();
            }
        }
    }     

In this code segment, I am using requestContext.RouteData.Values["controller"] to extract controller name from route collection. I have used Activator class which uses reflection. Release method is used to dispose controller object.

Note: I didn’t handle exception in this segment because it was not worth it. I would suggest the viewer to use their own exception handler.

We can extend it as much as we can do. It always depends on our business requirements.

The final step I am going to explain using code is how to register custom controller factory.

MVC framework has ControllerBuilder class which allows us to set custom controller factory using its static property.

We must set custom controller factory at the startup in Global.asax file inside Application_Start() method with the following code segment:

ControllerBuilder.Current.SetControllerFactory(typeof (My_Controller_Factory)); 

Sometimes, it is enough to just override the existing controller factory but not always.

Apart from overriding default controller factory, some =times we must extend RouteHandler mechanism too.

For this session, I am going to end it in this point only. But I will try to continue this and will explain Route handler and how to customize Route handler.

Source

  1. CodeProject itself is a great source
  2. http://www.stackoverflow.com
  3. http://www.dotnetcurry.com
  4. http://dotnet.dzone.com   

History : 

* Revised on 26 Feb 2014 : un-commented code segment. 

Need Suggestions

Your comments and suggestions would be greatly appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anupam Singh_
Software Developer
India India
Apart from JUGAAD technology Smile | :) .
I am practicing and exploring Microsoft Technology like ASP.NET MVC, WCF ,Ms SQL Server..
I have also studied Ruby on Rails Framework, C++ , JAVA and many more.
But I am a great fan of C# and I am stick with it for now.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 24 Feb 2014
Article Copyright 2014 by Anupam Singh_
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid