What are good candidates for base controller class in ASP.NET MVC?

There are no good uses of a base controller class.

Now hear me out.

Asp.Net MVC, especially MVC 3 has tons of extensibility hooks that provide a more decoupled way to add functionality to all controllers. Since your controllers classes are very important and central to an application its really important to keep them light, agile and loosely coupled to everything else.

  • Logging infrastructure belongs in a
    constructor and should be injected
    via a DI framework.

  • CRUD scaffolding should be handled by
    code generation or a custom
    ModelMetadata provider.

  • Global exception handling should be
    handled by an custom ActionInvoker.

  • Global view data and authorization
    should be handled by action filters.
    Even easier with Global action filters
    in MVC3.

  • Constants can go in another class/file called ApplicationConstants or something.

Base Controllers are usually used by inexperienced MVC devs who don’t know all the different extensibility pieces of MVC. Now don’t get me wrong, I’m not judging and work with people who use them for all the wrong reasons. Its just experience that provides you with more tools to solve common problems.

I’m almost positive there isn’t a single problem you can’t solve with another extensibility hook than a base controller class. Don’t take on the the tightest form of coupling ( inheritance ) unless there is a significant productivity reason and you don’t violate Liskov. I’d much rather take the < 1 second to type out a property 20 times across my controllers like public ILogger Logger { get; set; } than introduce a tight coupling which affects the application in much more significant ways.

Even something like a userId or a multitenant key can go in a ControllerFactory instead of a base controller. The coupling cost of a base controller class is just not worth it.

Leave a Comment