Global.asax event handling internals (part 1 of 3)

Some days ago I and another project member were seeing the best way to catch unhandled exceptions in ASP.NET.

We found the Global.Application_Error method in Global.asax which them.

Besides Application_Error, Visual Studio creates some other methods for handling events in Global.asax:

 

protected void Application_Start(Object sender, EventArgs e)

{

}

protected void Session_Start(Object sender, EventArgs e)

{

}

protected void Application_BeginRequest(Object sender, EventArgs e)

{

}

protected void Application_EndRequest(Object sender, EventArgs e)

{

}

protected void Application_AuthenticateRequest(Object sender, EventArgs e)

{

}

protected void Application_Error(Object sender, EventArgs e)

{

}

protected void Session_End(Object sender, EventArgs e)

{

}

protected void Application_End(Object sender, EventArgs e)

{

}

 

All the methods have a signature compatible with the EventHandler delegate but none of the events are declared in Global or HttpAppliaction.

So how are the methods bound to the events?

If you ask it to Doug Purdy (the Remoting’s father e one of the fathers of Indigo), he would probably answer that it is magic as he did when answering a question of mine about Remoting. But I (whom am not the father of Indigo or Remoting and started studying ASP.NET a couple of weeks ago) will answer:

It does the binding during application initialization using a lot of Reflection.

Handed with my debugger (Visual Studio) and .NET Reflector, I found an internal class called HttpApplicationFactory which is who initializes the application.

But before instantiating an object from Global (in fact a class derived from Global created automatically), HttpApplicationFactory enumerates all Global’s methods within the ReflectOnApplicationType method and with ReflectOnMethodInfoIfItLooksLikeEventHandler() inserts every method that has as name that looks like an event handler in a list.

This list will be enumerated by HttpApplicaton. HookupEventHandlersForAppplicationAndModules to find events whose name is “compatible” with the methods found in Global.

When a compatible name is found, Reflection is used again to bind the method to the event.

As a piece of code worth more than “ new Regex(@"((w+)s)*").Matches(milPalavras).Count” words, follow to the next post.

 

PS.: This is due to the fact that MSN Spaces has a limit on the post’s sizes.

This entry was posted in ASP.NET. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s