HTTPModules and Global.asax -- ASP.NET Page Life cycle

Peru picture Peru · Nov 10, 2012 · Viewed 9.1k times · Source

I have read the beautiful article about Asp.Net Page life Cycle http://www.codeproject.com/Articles/73728/ASP-NET-Application-and-Page-Life-Cycle.

My understanding is the request passes through MODULE(BeginRequest,authentica,author,prehandler...) HANDLER(Proccessrequest) PAGE(Init,viewstate,load,render,......,unload) MODULE(Posthandler,postrequescache,Endreques).

Where exactly does the Global.asax(Application_start,Application_begin,....) comes in the above flow ? Clarity on this will really help

Does Init function called first or Global.asax functions ?

Thanks for your valuable time.

Answer

Mark Rucker picture Mark Rucker · Jul 3, 2013

ASP.NET applications in IIS are structured like my image below. I know it is probably scary looking but the names should sound familiar. Hopefully the familiar names make it a little more digestible.

I'm not going to rehash in words the structure you see below. The picture does a better job than I could ever say in sentences. Instead, I'll jump right in to the implications the image has for your questions.

Scary Stuff

App Domain
What is an App Domain? It is as a private allotment of system memory for an application. All code inside the domain uses the allocated domain memory. This means static types and references are shared in a domain. No code outside of the domain can access this domain's memory.

Every ASP.NET application runs inside an App Domain for each App Pool it belongs to. This one-to-one relationship holds true regardless of the thread count in an App Pool.

Global.asax
What is Global.asax? At its simplest it is a .NET class that inherits from System.Web.HttpApplication. HttpApplication gives Global.asax the smarts to guide all HTTP Requests through the request pipeline. It will fire all the request life-cycle events and call ProcessRequest on the handler.

Each ASP.NET application will create multiple instances of HttpApplication (Global.asax). When a request is received it will be handed to one of the HttpApplication instances. The request will then stay with the same HttpApplication instance for its lifetime. This means there is one HttpApplication instance per request being handled. Every HttpApplication instance can, and will, be reused to handle many requests during its lifetime.

Aplication Events
Where do the Application events like Application_Start tie in? That depends since some of these events refer to the App Domain and some to HttpApplication. Application_Start and Application_End refer to the start and end of the App Domain. The rest of the Application events (e.g. Application_Begin) refer to the life-cycle of an HttpApplication instance.

More Information
For more information I suggest this MSDN article and this non-MSDN article.