Rules

Secret ingredients to quality software

Edit
Info

Do you use startup tasks in the ~/App_Start folder instead of putting code in Global.asax?

Created on 07 Mar 2013 | Last updated by Tiago Araujo on 02 Mar 2017 09:54 PM (about 4 years ago)

Adding code to the Application_Start method in the Global.asax file is the easiest and most straight-forward approach for executing startup logic, however, this code should be encapsulated in static methods outside the Global.asax file. Doing this helps provide cleaner code and encourages proper adherence to the Single Responsibility principle.

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );        }
}

Figure: Bad Example – Logic is implemented in the Application_Start method which breaks the Single Responsibility Principle

startup task
Figure: Good Example – Startup tasks are called from the Application_Start method but are located in the App_Start folder

Damian BradyDamian Brady

We open source. This page is on GitHub