23

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.

Andy
  • 2,670
  • 3
  • 30
  • 49

2 Answers2

16

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.

mckamey
  • 17,359
  • 16
  • 83
  • 116
  • Is there an event (or similar) which I can hook in to for Applcation_Start since I need to have my HttpApplication class outside of the website ? – Mark Broadhurst Jan 27 '10 at 16:37
  • 1
    Just implement a method `Applcation_Start` in Global.asax.cs and it will be automatically wired up and called at start time. http://msdn.microsoft.com/en-us/library/ms178473.aspx – mckamey Jan 28 '10 at 08:02
  • Keep in mind, though, that events like `AuthenticateRequest` or `AcquireRequestState` don't fire if you register event handlers in `Application_Start()`. You may want to register them in `Init()` which is an override to `HttpApplication`. – Manfred Oct 05 '14 at 06:17
9

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).

consept
  • 91
  • 1
  • 2