ASP.NET HttpApplication lifecycle

2020-04-02 08:46发布

问题:

Does the HttpApplication class extended by Global.asax.cs exist for the lifetime of the application?

At what point can instances be created/destroyed?

I'm experiencing application_start firing twice, it appears to be something to do with the app pool recycling and making requests part way though this process. I've not quite debugged it and I dont have time at the moment to do so in depth. So, in relation to the above question, is the following a safe solution?

public class MvcApplication : System.Web.HttpApplication
{
    public static object syncLock = new object();
    public static bool applicationBooted;

    protected void Application_Start()
    {
        if(!applicationBooted)
        lock (syncLock)
        if(!applicationBooted)
        {
            // bootstrap here
            applicationBooted = true;
        }
    }
}

回答1:

If you are seeing the event twice in your logs, check that the application pool is set to spawn a single worker process. Each worker process will create its own instance of the HttpAppication.



回答2:

From the MSDN online page,

After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

ASP.NET Application Life Cycle Overview



标签: asp.net