81

I am wondering under what circumstances I should be putting application initialisation code in Application_Start() vs Init() in my Global.asax file?

The distinction between the two doesn't seem very obvious to me, other than Application_start gets called first, then Init().

  • Why would I use one over the other?
  • Does it really make a difference?
  • What changes in the application state between the two events?

So far the only real pointer I can find is that IHttpModule only has an Init() method, so if what I'm doing may at some point be better suited to implement IHttpModule I should use the Init() method of Global.asax, if nothing else for consistency.

roryf
  • 29,592
  • 16
  • 81
  • 103

2 Answers2

90

From the MSDN docs:

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

Init:

Called once for every instance of the HttpApplication class after all modules have been created.

UPDATE: if you need to make sure a certain code is called only once in the app. lifecycle, Application_Start is a better solution. Examples: configuring log4net?

Igor Brejc
  • 18,714
  • 13
  • 76
  • 95
  • 5
    Bit of a follow-up question: when is an instance of HttpApplication created? I'm assuming each time the worker-process is restarted and it will contain one instance for each worker-thread? – roryf Apr 06 '09 at 11:58
  • 3
    @roryf - asp.net maintains a pool of application instances that can be resused. Under the covers, requests are serviced using the CLR threadpool and incoming requests will be queued beyond a certain threshold. I doubt they initialize the application instance pool to that threshold level since most sites won't see that kind of traffic. I suspect they create the pool with a small number of instances and then increase the size of the pool as demand ramps up. – Joel Fillmore Jun 01 '11 at 21:37
12

Yes

There are differences between them. Application_Start() event is called just one time while Init() method is called on each time when instance of the application is created.

David Gardiner
  • 16,892
  • 20
  • 80
  • 117