Dejan
Dejan

Reputation: 10323

First Web API request triggers execution of Application_Start

I'm having a Web application that also integrates a Web API. Just today I've found myself surprised to see that the first REST request on the Web API re-triggers the execution of Application_Start (although it has been run already when starting the web page). After reading ASP.NET HttpApplication lifecycle and ASP.NET Application Life Cycle Overview, it seems that the REST request is spawning a new HttpApplication.

Further, on the MSDN it says:

The first time that an ASP.NET page or process is requested in an application, a new instance of the HttpApplication class is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.

This sounds to me that each request could potentially spawn a new HttpApplication and that thus, Application_Start must be written in a re-entrant or idempotent way. Is this conclusion right?

In my concrete case, I'm initializing a log writer in Application_Start which fails the second time because the file is already being used. I guess in the case of an application pool recycling this wouldn't be a problem, as the resources are freed in-between.

Upvotes: 1

Views: 2299

Answers (1)

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16013

You can read further down on the provided link

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.

So there is no need to write Application_Start in a re-entrant or idempotent way.

Furthermore Application_Start is not called on the recycling of IIS. It gets called on the first request after recycling when the application is actually loaded by IIS.

As for your error, make sure you're disposing off your logger on Application_End so the file handle gets released.

Upvotes: 1

Related Questions