Question

I'd like to inherit all my controllers from a custom base class that I write myself. I can change the line every time I add a new controller, but it would be nicer if I could somewhere specify the default value that gets set there. That way I wouldn't need to worry about forgetting this, and other people who get added to the project later on would have an easier time.

Is there any way to achieve this?

Was it helpful?

Solution

You can customize the T4 template that gets used when the Add Controller action gets invoked. Basically you would have to copy the template from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates\AddController\Controller.tt to '~\CodeTemplates\AddController\Controller.tt` in your project file.

More info available here (scroll down to "Adding and Customizing Scaffold Templates")

OTHER TIPS

You could do this using namespaces: create a class called Controller in the same namespace as your controllers, e.g.:

namespace UI.Controllers
{
    public class Controller : System.Web.Mvc.Controller
    {
        //Code here
    }
}

and then the standard unqualified references to Controller will reference your base class instead of the System.Web.Mvc.Controller one.

Might get confusing though - I'd rather just have to remember to reference the base class.

Yup that's an easy task to do. First create a class called "BaseController" for example which inherits from Controller. Then all your controllers would inherit from BaseController.

EDIT: I think that using a T4 template to generate your costume controller (called BaseController or maybe Controller - whichever you prefer) would also work. I've seen Scot Hanselman do something similar in one of his talks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top