Sunday, 31 August 2014

Undertanding MVC LifeCycle and Best practices about MVC


The MVC stands for “Model-View-Controller” and describes a architectural design pattern for web applications development. It is a kind of implementation pattern for a multi-tier application and uses basically the well-known three-tier-architecture in software design.

Note: MVC is not specific to .NET. MVC architectural pattens is used with java,ruby on rails android framework ...I mean this pattern can be used with any most of the frameworks and .net provides you out of box templates for creating MVC Applications

ASP.NET MVC is implementing that kind of application design for ASP.NET web development. When creating an ASP.NET MVC application the communication between server and client will be state-less again like other server technologies, there is no session state saved in the servers responses. Fact is that web-form is such a architectural pattern which gives you option of session maintenance on server side because of which application performance results in degrade.
Although it is possible to create web applications following the MVC design pattern on your own or using the “classic” ASP.NET web application template, ASP.NET MVC is the very strict way to enforce following the MVC design pattern in your implementation. With ASP.NET MVC 3 and its new view rendering engine Razor I’ll have a closer look at MVC.
Follow me on my first steps with ASP.NET MVC.

ASP.NET MVC 5 is the latest version of the popular ASP.NET MVC technology that enables you to build dynamic websites using the Model-View-Controller technology.
The ASP.NET MVC 5 Framework is the latest update to Microsoft’s popular ASP.NET web platform. It provides an extensible, high-quality programming model that allows you to build dynamic, data-driven websites, focusing on a cleaner architecture and test-driven development.
ASP.NET MVC 5 contains a number of improvements over previous versions, including some new features like
Improved user experiences
Native support for JavaScript libraries to build mufti-platform CSS and HTML5 enabled sites

This article focuses on basic and core functionality of MVC.
In this article, we will be taking an overview of some of the exciting fundamental features
  • LifeCycle
  • Attribute Routing 
  • controller best practices

ASP.NET MVC In-Depth: The Life of an ASP.NET MVC Request

The purpose of this ARTICLE is to describe each step in the life of an ASP.NET MVC request from cradle to grave.  If I don’t understand the page request life cycle, It is hard to understand MVC.

There are five main steps that happen when you make a request from an ASP.NET MVC website:

Step 1 – The RouteTable is Created

This first step happens only once when an ASP.NET application first starts. The RouteTable maps URLs to handlers.When application starts at first time, it registers one or more patterns to the Route Table to inform the routing system what to do with any requests that match these patterns An application has only one Route Table and this is configured in RouteConfig.cs of App_Start Folder and setup in the Global.asax file of the application as show below:-

After this The UrlRoutingModule intercepts every request and creates and executes the right handler which is MVCHandler.I think it is better to understand functionality of Handler first if you feel confused about word handler.
or as developers point of view the difference between them is : one implements IHttpModule interface another implements IHttpHandler interface.

Module participates in the request processing of every request

Handler is responsible for handling the request and producing the response for specific content types.

Step 2 – The MvcHandler Executes

It is the responsibility of MvcHandler class for generating the response for the ongoing request being processed. The MvcHandler class receives information about the ongoing request from the RequestContext passed to its constructor, in the implementation of the GetHttpHandler() method in the MvcRouteHandler class. The MvcHandler class implements following 3 interfaces : IHttpAsyncHandler

MvcHandler’s ProcessRequest method’s first step would be get an instance of the Controller and the IControllerFactory using the ProcessRequestInit method. MvcHandler uses the Controller factory instance and tries to get a IController instance. If successful, the Execute method is called.

//D# View
protected internal virtual void ProcessRequest(HttpContextBase httpContext)
    SecurityUtil.ProcessInApplicationTrust(delegate {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);

Step 3 – The Controller Executes

The controller determines which controller method to execute, builds a list of parameters, and executes the method.The IControllerFactory could be the default controller factory or a custom factory initiailized (set) during the Application_Start event, as shown below:

protected void Application_Start()
   ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());

All controllers inherit from the Controller base class, which in turn inherits from the ControllerBase which implements the IController interface. When the MvcHandler calls the Execute method in ProcessRequest using the IController instance, it executes the Execute method in ControllerBase, which calls ExecuteCore which is implemented in Controller as in ControllerBase its an abstract method. ExecuteCore finds the appropriate action method and proceeds. Just for the kicks here is an extract for this method from the reflector.

// From D#
protected override void ExecuteCore()
        string requiredString = this.RouteData.GetRequiredString("action");
        if (!this.ActionInvoker.InvokeAction(base.ControllerContext, requiredString))

Step 4 – The RenderView Method is Called

Typically, a controller method calls RenderView() to render content back to the browser. The Controller.RenderView() method delegates its work to a particular ViewEngine DEPENDS which engine is configured.

Controller’s best practices

  1.   Delete the  exiting all classes/controllers
  2.   Keep you Controller very think just for what is meant..No extra functionality definition in controller class .i mean Controller should be only responsible for:
    • Validating Input
    • Calling Model to prepare the view
    • Return the view or redirect to another action
  3.   Prefer to use ViewModel per view and Strongly ViewModel rather than ViewData.
  4.  Choosing view engine should be done with care. Default view engine is ASPX and if your application is just  migration of ASP.NET Web-form then you can keep it as aspx view engine  otherwise make sure you choose better one . there are lots of 3rd party views like spark.. which is more preferable because of its rich future in terms of markup control.
  5.  Use IOC (Dependency injection) to adhere best practice like loosely coupled system and easy Test driven development practice.
  6.  Decorate your Action Methods with Proper AcceptVerbs Attribute.ASP.NET MVC is much more vulnerable comparing to Web Forms. Make sure the action methods that modifies the data only accepts HttpVerbs.Post. Better is use HttpVerbs.Post for all data modification actions and HttpVerbs.Get for data reading actions
  7. Decoratemost frequently used Action Methos with OutputCache attribute
    [AcceptVerbs(HttpVerbs.Get), OutputCache(CacheProfile = "EmployeeChart")]
    public ActionResult EmployeeChart(string empId Salary salary, int? page)
Hope this helps