SSW Foursquare

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

Last updated by Tiago Araújo [SSW] almost 2 years ago.See history

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

We open source. Powered by GitHub