Sunday 13 January 2013

Asp.Net App_Code AppInitialize non-documented featured (invoked before Application_Start)

I was looking for a way to apply website specific customizations to TeamMentor (i.e. code that should be website specific, not TeamMentor.Corelib.dll specific).

The key requirements are that this code:
  • is executed as soon as possible (and only once), 
  • is not placed inside the Global.asax file and 
  • it can be used to apply targeted customization to the code in TeamMentor's CoreLib.dll 
I found exactly what I was looking for in the AppInitialize undocumented feature of Asp.Net.

Basically, if on the (dynamically compiled) App_Code folder we add a class

image

with a public static method called AppInitialize

image

That method will be called before the Global.asax Application_Start (which means that it is the perfect place to put website specific settings like the one shown above).

I also added some Event’s to the main TeamMentor.CoreLib which allow the hook of events like the Global.asax BeginRequest.

image

The code above will write “<h1>Custom code</h1>” on all requests that are not .js, .ashx, .asmx, . jpg and .gif.

This works on the local Cassini server and on IIS (see below the CI version created on Azure)

image

In the title of this post I mentioned that this was undocumented because there doesn’t seem to be any offical public information about this:

image

The only information out there seems to come from the startup - When AppInitialize method get invoked in ASP.NET? post:

image