Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HttpApplication constructor called several times

Can somebody explain why the constructor of a custom class derived from HttpApplication is called several times upon application startup?

My code structure is the following:
- My Global class in global.asax derives from CustomApp class.
- The CustomApp class derives from HttpApplication class

The Global class is created at startup, but when I place a breakpoint in the constructor, it is invoked several times! I thought there should be only one instance of Application class created?

Am I wrong?

UPD: the web server can indeed create several HttpApplication instances to process multiple requests coming in at the same time. This becomes especially apparent when you place a breakpoint in the constructor of your HttpApplication descendant. Several requests will be pending from the client (http content, CSS files, etc) and to serve each of them the web server will create new instances of HttpApp. So, beware of this, when writing the application initialization logic.

like image 250
Andy Avatar asked Jun 06 '09 05:06

Andy


2 Answers

I believe the ASP.NET runtime may create more than one HttpApplication per application domain. So HttpApplication.Init and the Ctor may get called more than once.

If you want to have initialization code that only runs once, you should use the Application_Start event which will only be called once per app.

like image 134
mckamey Avatar answered Oct 22 '22 05:10

mckamey


Please have a look at a post global.asax in ASP.NET - it explains why there are multiple instances of the HttpApplication. Basically there are two pools: special and normal. Normal pool contains instances of the HttpApplication which are used by the requests (each requests has its own HttpApplication instance). Special pool contains HttpApplication objects used for application-level events (like Application_Start, Application_Error).

like image 9
consept Avatar answered Oct 22 '22 05:10

consept