Controller detailed learning course in asp.net mvc

Source: Internet
Author: User
Tags abstract constructor

In this paper we introduce the C,controller controller in the ASP.net MVC development model in detail.

1.Controller class

Controller's execution is embodied in the invocation of its Excute method, which defines only one Excute method in the IController interface, which is executed synchronously.

public interface icontroller{void Excute (RequestContext requestcontext);}

In order to be asynchronous, a Iasynccontroller interface is defined under the System.Web.Mvc.Async namespace, as shown in the following code

Public interface Iasynccontroller:icontroller
{
IAsyncResult beginexecute (RequestContext RequestContext, as    Ynccallback callback, object state);
void EndExecute (IAsyncResult asyncresult);
}

The


Iasynccontroller interface is derived from the IController interface, controller asynchronous execution through successive calls to Beginexcute and EndExecute methods. There is also a very important base class Controllerbase, the default all controller classes will inherit it, it is an abstract class, Controllerbase also implements the IController interface. This class shows the Excute method that implements the interface, and the Excute method of the implementation invokes the protected virtual method Excute, which continues to invoke the abstract method Excutecore method as the successor to the Controllerbase, The execution of controller must be done through the Excutecore method. The following is a code fragment for Controllerbase

Public abstract class Controllerbase:icontroller
{public
viewdatadictionary ViewData {get; set;}
Public dynamic ViewBag {get;}
Public tempdatadictionary TempData {get; set;}
protected virtual void Execute (RequestContext requestcontext);
protected abstract void Executecore ();
protected virtual void Initialize (RequestContext requestcontext);
void Icontroller.execute (RequestContext requestcontext);
}


The target controller returns a view as a response after execution, at which point Controller can pass TempData, ViewBag, ViewData to the view. From the definition you can see TempData and ViewData are returned to the dictionary structure of the data container, the difference is tempdata, such as its name, stored data is temporary, after one can not be used again, ViewData can be used many times. ViewBag can store dynamic objects, that is, any attribute can be specified, and the property name is the key of the data dictionary. There is also the ControllerContext class, where objects of this class can be viewed as encapsulation of RequestContext and controller objects. From the above definition of the Controllerbase class you can see that there is also a initialize method that has a RequestContext parameter that creates the ControllerContext object when it is executed. A protected virtual method Excute executes the Initialize method before executing the Excutecore method. The controller we created with VS actually inherits from the abstract controller class, and in VS you can see controller in addition to inheriting controllerbase classes, implementing IController interfaces and Iasynccontroller interfaces, Also implements the interface of 5 kinds of filters. In addition, it implements some other interfaces, such as IDisposable interface, MVC controller activation system will call its Dispose method to complete the corresponding resource recycle after controller execution.

2. With asynchronous, Controllerfactory, Controllerbuilder

The definition of controller from an abstract class shows that it implements the Iasynccontroll interface, which inherits from the interface IController interface, so controller can either achieve synchronization (Excute) or asynchronous mode ( Beginexcute/endexcute method). The Controller class has a Disableasyncsupport property, the default is false, and if it is set to true, it executes only in a synchronous manner, and False when it is performed asynchronously.

asp.net mvc defines the corresponding factory for controller activation, that is, the Controllerfactory class, all controllerfactory classes implement the Icontrollerfactory interface, such as the following code fragment

Public interface icontrollerfactory
{
icontroller createcontroller (RequestContext requestcontext,string    Controllername);
Sessionstatebehavior Getcontrollersessionbehavior (RequestContext requestcontext, String controllerName);
void Releasecontroller (IController controller);
}


Controllerfactory will be responsible for creating and releasing the Controller object's work. The creation is embodied in the Createcontroller method, and the release is in the Releasecontroller method. There is also a Getcontrollersessionbehavior method that returns an enumeration value of type Sessionstatecontroller. Its 4 properties are: Default, which indicates that the requested session state behavior is determined by using the asp.net logic; requeired enable full read/write session state behavior for the request; ReadOnly: Enable read-only session state behavior for requests; disabled disables session state. The exact behavior depends on the HTTP context, HttpContext static property current.

The controllerfactory used to activate the Controller object is eventually registered through Controllerbuilder into the asp.net MVC framework.

public class Controllerbuilder
{public
controllerbuilder ();
public static Controllerbuilder current {get;}
Public hashset<string> defaultnamespaces {get;}
Public icontrollerfactory getcontrollerfactory ();
public void Setcontrollerfactory (Icontrollerfactory controllerfactory);
public void Setcontrollerfactory (Type controllerfactorytype);
}



Controllerbuilder's current returns the object currently in use, and two overloaded setcontrollerfactory methods implement Controllerfactory registration. The difference is that the first registration is a specific Controllerfactory object, and the second registers a controllerfactory type. If we register for the second way, then getcontrollerfactory creates the object by calling the Activator static method CreateInstance at execution time. That is to say, each call to the Getcontrollerfactory method is always accompanied by an instantiation of the object, but the MVC mechanism does not cache the object of the instance. Therefore, it is better to adopt the first method, which will get the specific object to return directly from Getcontrollerfactory.

We know that the routing system generates a Routedata object after parsing the request, its values attribute holds the name of the target controller, and if there is no namespace and a controller name with the same name, an exception is reported. The controller activation system provides us with 2 ways to raise the priority of namespaces: The first is specified when a route is registered, The namespace list is saved in the RouteValueDictionary object represented by the Datatokens property of the route object (where you can also specify a fallback namespace) The other way is to specify the Defaultnamespaces property in Controllerbuilder, ControllerBuilder.Current.DefaultNamespaces.Add ("namespace"). However, the former has a higher priority.

3.Controller activation and routing

The routing system can be considered as the first barrier after the request is distributed by IIS to the ASP.net pipeline, and then learn how the controller activation system and the routing system are organically combined. As we know from the previous knowledge, the entire ASP.net routing system is based on a httpmodule called UrlRoutingModule, which dynamically maps a HttpHandler to the current request by registering HttpApplication. That is, the request is routed through the global routing table and a Routedata object is generated, and then the Routehandler of the object is used to get the HttpHandler that is eventually mapped to the current request. The Routehandler object is a Mvcroutehandler object in the MVC mechanism. So, the simplest thing we can see is that the Routedata Mvcroutehandler object creates the HttpHandler object. Let's take a look at Mvcroutehandler.

public class Mvcroutehandler:iroutehandler
{public
mvcroutehandler ();
Public Mvcroutehandler (Icontrollerfactory controllerfactory);
Protected virtual IHttpHandler Gethttphandler (RequestContext requestcontext);
Protected virtual Sessionstatebehavior Getsessionstatebehavior (RequestContext requestcontext);
}


The Controllerfactory object is maintained in the Mvcroutehandler, which is specified in the constructor, and if not specified, the Getcontrollerfactory method of the current Controllerbuilder object is invoked. In addition to getting the HttpHandler object, Mvcroutehandler also sets the current HTTP session state, which gets the name of the target controller from the RequestContext Routedata object. This name and the RequestContext object will call Controllerfactory's Getcontrollersessionbehavior method as a parameter to get an enumeration of type Sessionstatebehavior. Finally, the session state is set. The Routehandler property of the Routedata is originally derived from the corresponding routing object, and for the route object that calls the RouteCollection extension method Maproute registered, Its corresponding Routehandler is a Mvcroutehandler object, because the specified controllerfactory is not displayed when the object is created. Therefore, the resulting controllerfactory by invoking the Getcontrollerfactory method of the current Controllerbuilder object is used by default.

The Gethttphandler method will eventually retutn new Mvchandler (RequestContext); The controllerfactory of the Getcontrollerfactory method through Controllerbuilder is only Mvcroutehandler to get the session state mode. And only Mvchandler is real. Create a target controller object. Because Mvchandler implements both the IHttpHandler and IHttpAsyncHandler interfaces, all of them are always executed asynchronously, The final activation of controller is the target controller object that is activated by the Controllerfactory object provided by the current Controllerbuilder. Finally Mvchandler will implement the release cleanup work.

4.Controller Default Activation

The activation of the Controller object is ultimately done through the registered Controllerfactory, When we do not show the Setcontrollerfactory method that invokes Controllerbuilder to specify the Controllerfactory object, The controller activation system uses a Defaultcontrollerfactory object to activate the target controller, which is the default controller activation mechanism used by asp.net mvc.

The target controller object is activated on the premise that it obtains the true type of the target controller, including some routing information of the parsing controller type in defaultcontrollerfactory, such as the name of the controller, namespace, the default namespace for the current Controllerbuilder, and so on. You may feel that with these 3 conditions, you should be able to get the controller instance by name, however this is not possible. First, the variable value of the controller name in the Routedata is case-insensitive, while the type name is case-sensitive; for namespaces, learning from the previous study is typically followed by a name. * So we can't resolve the type of target controller by name. The right thing to do is to Defaultcontrollerfactory call BuildManager's static method Getreferencedassemblies get all the available assemblies, and then pick out the types of all internship interface IController , and finally through the controller name and namespace to match the target name, simply put, the latter way to ensure that the target controller and namespaces have not changed, is the most real data.

For performance reasons, all valid controller types that are parsed are cached globally. The cache for the controller type is also implemented in Defaultcontrollerfactory, and the list is persisted, which is still present after the application restart. The controllerfactory used to activate the target controller object is not only used to create the target controller object, but also has 2 features: one is to release and reclaim the activated controller object, The other is to return the Sessionstatebehavior enumeration object that controls the current session state behavior through the Getcontrollersessionbehavior method.

5.IOC Application

Control reversal, referred to as the IOC. When I was learning mvc, I heard the word from the teacher, but I didn't know the word deeply and I had to conquer it today. The meaning of the IOC is simply that the application itself is not responsible for the creation and maintenance of the dependent objects, but the task is given to the external container, so that the application is transferred from the application to the external IOC container, so that the control is reversed, that is, the control reversal is reversed to others. For example, Class A needs to use instances of Class B, while the creation of B instances is not owned by a, but created by an external container. This idea is of great significance in realizing the activation of target controller.

IOC and Di (Dependency injection) are often linked together. DI is an external container that dynamically injects dependent objects into the assembly at run time. Mr. Chiang, the author of the book, prefers to divide dependency injection into one mapping and 3 injections, and I feel good about it.

(1) A mapping is a type mapping, although we can invoke the method of an object through an interface or abstract class, but the object itself is a specific type, so a type registration mechanism is needed to resolve the matching relationship between the interface/abstract class and the implementation class/specific subclass.
(2) constructor injection, the IOC container intelligently chooses and invokes the appropriate constructor to create the dependent object. If the selected constructor has the appropriate parameters, the IOC container resolves the registered dependencies and creates the corresponding parameter objects on its own before calling the constructor.
(3) Property injection, if you need to use a property of a dependent object, the IOC automatically initializes the property after the dependent object is created.
(4) method injection, if the dependent object needs to invoke a method for the corresponding initialization, the IOC container automatically invokes the method after the object is created. Let's look at an example

public interface ia { } public interface ib { } public interface
 ic { } public interface id { } public class a : ia {     public ib b { get; set; }     public &NBSP;ID&NBSP;D&NBSP;{&NBSP;GET;&NBSP;SET;&NBSP}     //Constructor Injection     public  a (ib b)     {        this.
b = b;
&NBSP;&NBSP;&NBSP;&NBSP}     //Property Injection     public IC c;     public ic c     {         get { return  c; }         set &NBSP;{&NBSP;C&NBSP;=&NBSP;VALUE;&NBSP}          //method Injection      publIc void initialize (Id d)  {&nbsp}} 


We know that when a user requests to come, if it involves data services, controller will call model directly, if the need to render business data, then the corresponding data will be converted to ViewModel, at this time controller to model is directly dependent. The IOC's ideas can now be applied to the controller activation system, and the degree of dependency between controller and model will be reduced if the IOC is used to provide the Controller object for the processed request. We can also define the Imodel interface to abstract the model in this way, so that controller relies on this abstract model interface rather than the concrete model implementation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.