When creating an ASP.NET Mvc project in Visual Studio, a Global.asax
& Global.asax.cs
will be created. In this .cs file you will find the standard Application_Start
method.
My question is the following, how is this function called? because it is not a override. So my guess is that this method name is by convention. The same goes for the Application_Error
method.
I want to know where these methods are hooked. Because I write those methods (not override them) I couldn't find any documentation on them in MSDN. (I found this page but it only tells you to hook to the Error
event and shows a Application_Error(object sender, EventArgs e)
but not how the Event and the method are linked.)
//Magicly called at startup
protected void Application_Start()
{
//Omitted
}
//Magicly linked with the Error event
protected void Application_Error(object sender, EventArgs e)
{
//Omitted
}
It isn't really magical.. the ASP.NET Pipeline wires all of this up.
You can see the documentation regarding this here.
Specifically you will be interested in the parts below:
An
HttpApplication
object is assigned to the request.
Which consists of a list of events that are fired and in what order.
There are links all over that page (too many to contain here) that link off to various other pages with even more information.
ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as
Application_BeginRequest
. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page'sPage_Load
event.
Source: http://msdn.microsoft.com/en-us/library/ms178473.aspx
To demystify the 'magic' of the accepted answer, the ASP.Net pipeline is automagically binding the HttpApplication
events to the methods with the Application_EventName
in the class. If (much like me) you would rather see the events explicitly bound to a handler these can be bound by overriding HttpApplication.Init()
and Visual Studio will generate the handler method with the correct signature.
public override void Init()
{
this.BeginRequest += MvcAppliction_BeginRequest;
}
private void MvcApplication_BeginRequest(object sender, EventArgs e)
{
...
}
There is an example of this method of binding events
ASP.Net itself creates it. Here is the flow as per MSDN -
Here is the reference - ASP.Net Application Life Cycle.
From the reference - ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With