C# – Do I need a Global.asax.cs file at all if I’m using an OWIN Startup.cs class and move all configuration there

asp.netasp.net-mvcasp.net-mvc-5cowin

Let's say for example in a brand new ASP.NET MVC 5 application made from the MVC with Individual Accounts template, if I delete the Global.asax.cs class and move it's configuration code to Startup.cs Configuration() method as follow, what are the downsides?

public partial class Startup
{
     public void Configuration(IAppBuilder app)
     {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ConfigureAuth(app);
    }
}

The upsides for me is that when upgrading ASP.NET 4 applications to ASP.NET 5 and using pieces that now must be configured in the Startup.cs class, I'm not doing dependency injection and other configuration in two different classes that seem related to starting up, and configuration.

Best Answer

Startup.Configuration gets called slightly later than Application_Start, but I don't think the difference will matter much in most cases.

I believe the major reasons we kept the other code in Global.asax are:

  1. Consistency with previous versions of MVC. (That's where everybody currently expects to find this code.)
  2. Ability to add other event handlers. In Global.asax, you can handle other methods like Session_Start and Application_Error.
  3. Correctness in a variety of authentication scenarios. The Startup.Configuration method is only called if you have Microsoft.Owin.Host.SystemWeb.dll in your bin directory. If you remove this DLL, it will silently stop calling Startup.Configuration, which could be hard to understand.

I think the third reason is the most important one we didn't take this approach by default, since some scenarios don't include having this DLL, and it's nice to be able to change authentication approaches without invalidating the location where unrelated code (like route registration) is placed.

But if none of those reasons apply in your scenario, I think you'd be fine using this approach.

Related Topic