7

In ASP.NET WebAPI there is a method called ApplicationStart in the global.asax.cs file which is automagically called when the application started. How is this called?

The reason I ask is I would like to add an Application_End method to do any cleanup I need to do.

deanvmc
  • 5,957
  • 6
  • 38
  • 68
  • http://stackoverflow.com/questions/288350/application-end-global-asax – Mark Jones Dec 21 '12 at 16:03
  • It is important to note that these are only called if you are running your WebApi application within IIS. If you switch over to self host (OWIN), this is gone. – LRFalk01 Jun 13 '15 at 00:15

2 Answers2

14

ASP.NET WebApi is no different than ASP.NET when it comes to the Global.asax methods. These methods are discovered via reflection by the IIS application pool worker when the application is loaded and are then invoked at the appropriate times. There is a nice overview of this on MSDN, particularly the Global.asax methods like Application_Start() and Application_End().

Application_Start() is called by IIS when the application starts running inside the application pool. Generally, this happens when a request comes in for a resource within the application's domain. After all, the application has to be running for the request to be serviced.

Application_End() is called just before the application is unloaded or just before the application pool recycles. There are various triggers that cause the application pool to recycle.

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
Fls'Zen
  • 4,594
  • 1
  • 29
  • 37
2

MSDN has the full details here - http://msdn.microsoft.com/en-us/library/ms178473(v=vs.100).aspx, but the key bit that your interested in is:

Application_Start ..... Called when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.

Essentially it is invoked once per application life-cycle automatically by the application container (e.g. IIS).

Jon Malcolm
  • 461
  • 3
  • 12