MVC Life Cycle - Part 1

If you are an MVC developer, then this entire flow should be in your DNA. This not only solves complex problems; rather, it also makes an app more robust, future proof, maintainable and testable. Below, I have pasted a high level diagram for the same. Therefore, without wasting time, let us get started.


The entry point for any MVC application begins with routing. After that the ASP.NET platform receives the request and figures out how it should be handled by URL routing modules. The routing module is responsible for matching incoming URLs. All routes are associated with route handlers. So, if the request matches the defined route, then the MVC route handler will create an instance of MVC HTTP handler and retrieve the requested controller. MVC RouteHandler and MVC HTTPHandler are two classes and together they act as a gateway into the MVC Framework.

Then, MVC handler begins the process of initializing and executing the controller. The MVC framework handles converting our route data into a concrete controller which can handle requests. This is accomplished via the controller factory and activators, which are responsible for creating a controller instance. This is also the place where features like Dependency injection can be injected.

After the controller is created, the next step is action execution. A component called action invoker finds and selects the appropriate action method to invoke on our controller. Before this step model binding takes place, which actually maps the data from HTTP request to parameters on our action methods. Action filters are also called before and after the method produces an action result.

Now, after Action Result takes place, the next step is result execution. MVC separates declaring the result from executing the result. So, if the result is view type then view engine will be called and it's responsible for finding and rendering our view. If the result is not view, then action result will execute on its own. This result execution actually generates an actual response to that original HTTP request. So, this was the high level stuff.

Now, let us jump in the demo section. I have created a simple MVC 5 app as in the following screenshot.


One important point to understand here, is that at the heart of any MVC application class sits MvcApplication; you can find the same in global.asax file.
  1. using System.Web.Mvc;    
  2. using System.Web.Optimization;    
  3. using System.Web.Routing;    
  4.     
  5. namespace MVC_LifeCycle_Demo    
  6. {    
  7.     public class MvcApplication : System.Web.HttpApplication    
  8.     {    
  9.         protected void Application_Start()    
  10.         {    
  11.             AreaRegistration.RegisterAllAreas();    
  12.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);    
  13.             RouteConfig.RegisterRoutes(RouteTable.Routes);    
  14.             BundleConfig.RegisterBundles(BundleTable.Bundles);    
  15.         }    
  16.     }    
  17. }    
Now, this class derives from the ASP.NET "HTTPApplication" class. Now, HTTP application exposes a number of life cycle events which we can attach with event handlers and run our code. These events are:
  • ApplicationStart
  • BeginRequest
  • ResolveRequestCache
  • MapRequestHandler
  • AcquireRequestState
  • RequestHandlerExecute
  • UpdateRequestCache
  • LogRequest
  • EndRequest
  • ApplicationEnd
Therefore, every MVC application starts with the Application_Start event. This event fires when the app receives its first request and also allows us to perform global configurations before anything else gets started. I have already pasted one snippet above. This gives you the glimpse of various settings which we are doing before any MVC application starts. Here, we are also registering routes. Now, when you see the default implementation for the same, you will find the following code for the same.
  1. using System.Web.Mvc;    
  2. using System.Web.Routing;    
  3.     
  4. namespace MVC_LifeCycle_Demo    
  5. {    
  6.     public class RouteConfig    
  7.     {    
  8.         public static void RegisterRoutes(RouteCollection routes)    
  9.         {    
  10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    
  11.     
  12.             routes.MapRoute(    
  13.                 name: "Default",    
  14.                 url: "{controller}/{action}/{id}",    
  15.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }    
  16.             );    
  17.         }    
  18.     }    
  19. }  
Basically, RegisterRoutes method adds any route to a static collection of RouteTable class. Now, this is the collection of routes which URL Routing module will use to match any incoming URLs. Also, each of theses routes are also associated with the RouteHandler class. RouteHandler will provide HTTPHandler which will actually process incoming requests. Therefore, routes are registered inside route table before anything else happens at the Application_Start event. Below I have pasted screenshots while debugging the app.


As, we can see in the above screenshot, while running the app in debug mode, it first hit the Application_Start event. Once done with all global configurations, it then produced the default template for MVC app as shown below.


In order to test, the Application_End event, I just need to stop the IIS Express from the tray icon as shown below.



Once, I clicked on Exit, my breakpoint hit.



Now, upon successful execution, it also printed the same message in the Output window as shown below.



I hope you liked this small demo around MVC Life Cycle. We will delve further in coming sections. Till then stay tuned and happy coding.


Similar Articles