.net, C# tip, Clean Code, MVC, nuget, Solid Principles, WebActivatorEx

MVC Tip – Use WebActivatorEx to clean up your boot-strapping logic

The code snippet below shows the Application_Start method inside Global.asax.cs for a default MVC4 implementation.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
 
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
}

In the default implementation, it looks alright – not too messy. But I’ve seen some implementations of this method which are much longer – code to manage NInject registrations, Automapper, and View Engines. So I’ve learned to see this method as somewhere that quickly starts to violate the Single Responsibility Principle.

WebActivatorEx

It’s actually really easy to keep your code clean using WebActivatorEx. This is available as a nuget package that allows a class to be called either just before (or just after) application start-up.

You can install it to your project using the command in the Package Manager Console:

Install-Package WebActivatorEx 

Let’s look at de-coupling Application_Start from the reference to AuthConfig.RegisterAuth(). If we prefix the namespace with a call to WebActivatorEx (as shown below) this method will be called before the Application_Start method.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MvcApplication1.AuthConfig), "RegisterAuth")]
namespace MvcApplication1
{
    public static class AuthConfig
    {
        public static void RegisterAuth()
        {
            // ...authorization logic here...
        }
    }
}

I love this pattern because it means that the logic for calling the method at start-up is contained within the same method’s class. We don’t need to call it from the Application_Start method, so we’ve cleanly de-coupled two the classes from each other.