Advanced: How many times does HttpModule Init() method get called during application's life?
Init()
is called only once (per HttpApplication
instance)
After I tested this the inner workings of IHttpModule
initialization are as follows:
- Every
IHttpModule
is initialized at web application start by instatiating and a call toInit()
method HttpApplication
stores all module instances in itsModules
property- Modules are then reused for the whole life of an
HttpApplication
and are not discarded/reinitialized as long as the application is alive
So the best outcome is
You can't attach an IHttpModule
to application level events, but you can use its Init()
method as pseudo application start event delegate. Inside it you can execute any code that you'd usually put inside Application_Start
delegate in your Global.asax
.
You can also read detailed information about it in my blog post.
But be careful in real-life web server environment
But IIS uses something called application pools. And each pool can have an arbitrary number of HttpApplication
instances. Yes multiple. Application starting creates all these instances. Every one of them initializes their own list of modules but only the first one executes the Application_OnStart
event handler.
So whenever your module modifies some common shared resource, you should take extra measures to indicate that the first module has done that and others won't do it again. Read an additional blog post about it that will show you how and when to use thread locking with your module to make it actually act as an Application_OnStart
event handler. BTW: It's also possible to handle Application_OnEnd
event if you need to. ;)
Detailed blog post links
Application_Start is only run once for the lifetime of your application.
IHttpModule.Init is run for each instance of HttpApplication, before request processing begins. See the walkthrough. Init is where you can register events used to process the request.
An instance of HttpApplication can be reused for multiple requests. ASP.Net pools HttpApplication objects, so the Init will be called once for every new instance of HttpApplication