Understanding MVC Request Life Cycle: Part 1

This is my second post in series of MVC Getting Started, I hope you like it.
 
MVC Request Life Cycle
 
Life cycle is simply a series of steps or events used to handle some type of request or change an application state. Understanding the processing pipeline can help you better leverage the features available. MVC actually has two life cycles, the application life cycle and the request life cycle.
 
The application life cycle refers to the time at which the application process actually begins running IIS until the time it stops. This is marked by the application start and end events in the startup file of your application.
 
Request life cycle, refers to the sequence of events that happens every time an HTTP request is handled by our application.
 
Understanding Application Events
 
At the heart of every MVC project is a class called MVCApplication, which can be found in the global.asax project file. This class inherits from the ASP.NET HttpApplication class. HttpApplication exposes a number of Request Life Cycle events that we can attach event handlers to and run our own code.
 
Application Start and Application end. These two events run before and after any other events and allow our application to start or stop receiving requests. So every MVC application is brought to life by the Application Start event.
 
ApplicationStart event fires when the application receives its first request. It also allows us to perform global configurations before anything else happens, which we can see in the default implementation here. 
  1. protected void Application_Start() {      
  2.       AreaRegistration.RegisterAllAreas();       
  3.       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);       
  4.       RouteConfig.RegisterRoutes(RouteTable.Routes);       
  5.       BundleConfig.RegisterBundles(BundleTable.Bundles);       
  6. }       
In an MVC application you can use this method for various tasks, like registering areas or applying global filters, starting with MVC 4 you can also register script and CSS bundles. Most important use of this event is to register routes for the URL Routing Module to work with. The RegisterRoutes method adds any routes that we define to a static collection on the RouteTable class. 
  1. public static void RegisterRoutes(RouteCollection routes) {  
  2.              routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  3.              routes.MapRoute(                   
  4.                 name: "Default",url: "{controller}/{action}/{id}",  
  5.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );   
  6. }  
Routes also needs to have an associated RouteHandler class. The RouteHandler will provide ASP.NET with an HttpHandler that will actually process the incoming request after it’s been matched to a route. Routes are registered with the RouteTable inside the Application Start event before any other life cycle events happen.
 
MVC application class also exposes a method called Application End. It fires when our application stops and then no more requests can be received. This event fires if the application is intentionally shut down.
 
Working Example Demo
 
Create a new project
 
 
Select MVC
 
 
 
You will see a file called global.asax in solution window. 
 
 
 
This application was built off of an MVC 5 template, so inside of the Application Start Event we’re calling four other static methods.
 
Now let’s write a simple Application_End Event in the similar fashion Application_Start Event is present there. 
  1. protected void Application_End() {   
  2.       Debug.WriteLine("Application End Event Executed");   
  3. }   
If you see an error under the debug you can use Visual studio intellisense to figure it out. Debug is present under a different namespace called 
  1. using System.Diagnostics;   
Add it along with other namespace or use the shortcut using intellisense as below
 
 
 
Add breakpoints to the application as shown below so that we can see how the execution takes place. 

NOTE – You set a function breakpoint in source code by clicking in the left margin of a source code file, or by putting your cursor on a line of code and pressing F9.

 

So let’s run the application(F5) and you should hit a breakpoint. You will see that we hit a Application_Start event.

 

Now press F5 again to continue. Now trigger End Life Cycle event, we can just kill the application from our system tray at the bottom here. 
 
 
 
You can see how this triggers the Application End event.
 
 
 
Hit Continue and end the application.
 
Inside Application_Start method we have RouteConfig class. This class has a method called RegisterRoutes. The important thing to note is that we’re passing in the static RouteTable.Routes property to this method. Let’s drill down inside this method and see what we find. The RouteCollection that was passed in our RouteTable can be seen as a parameter. Next we’re calling the MapRoute method. 
  1. routes.MapRoute(       
  2. name: "Default", url: "{controller}/{action}/{id}",       
  3. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }   
  4. );  
Above code assign routes to the RouteTable collection that will be examined by the URL Routing Module. So here we’ve defined only one route and it’ll be the routing module’s job to compare any incoming URLs to see if they match. Every route needs an associated RouteHandler class to go with it. Now the RouteHandler class really only has one purpose, to retrieve the right HttpHandler for our request. The HttpHandler is what will actually execute to generate a response for that original request.
 
Well if we use IntelliSense to take a closer look at this MapRoute method, we can see that it’s actually an extension method. 

 

This method really just provides a short hand way of assigning MVC routes to the RouteCollection. It automatically associates the MVC RouteHandler to this route for us.

You can dig more depper by going through open source MVC project here

https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/RouteCollectionExtensions.cs

Thanks for reading.

Comments and feedback are welcome.