ASP. NET WEB API Controller creation process (ii)

Source: Internet
Author: User

ASP. NET WEB API Controller creation process (ii)

Objective

Originally this essay should be written out in the last week, because the body can not keep up with the rhythm of the cold fever powerless, such a cold fever life than death, but also the real experience of what is called a disease like mountain, sick to like a ladder. These two days the state is a little better, let me understand what is the cost of revolution, I hope we also take care of the body.

OK, or return to the topic, for the content of the previous article is only a partial knowledge of the creation process of the ASP. I will recall the contents of the previous article before the next chapter, and in this article, we want to see an entire creation process.


ASP. NET Web API controller creation, activation process

    • ASP. NET WEB API Controller creation process (i)
    • ASP. NET Web API Controller creation Process ( two )

Create, activate process

Figure 1


In the previous space we said that Apicontroller is created by the Httpcontrollerdispatcher type, which is only superficial, figure 1 shows the whole process of controller creation, let's think about what we said in the previous article, or we would consider it incoherent, Figure 1 is also explained at the same time in retrospect.

First, let's break down figure 1, which can be divided into two parts in Figure 1,

The first part of it is The part represented by the httpconfiguration type. 2

Figure 2


First to explain the httpconfiguration section, there are two properties in the Httpconfiguration type, the first is the Servicescontainer type of property services, The second is the property of the Idependencyresolver type Dependencyresolver, for the type of the Services property in the previous article I also said, is an IOC container, From the Httpconfiguration type point of view is an IOC container that relies on injection into httpconfiguration, which is almost identical to the Dependencyresolver attribute.

It's just that the services that are stored in this container are mostly types of basic work done in the ASP. NET WEB API framework.

As I said in the previous article, when we load the assembly of the Controller in the ASP. NET WEB API framework, we replace the default work items in the Services container with our own defined work items:

SelfHostServer.Configuration.Services.Replace (typeof (Iassembliesresolver),                   Newcustomassembliesresolver.loadspecifiedassembliesresolver ());

Here you can see the default defaultassembliesresolver type to run this work from Figure 2.

This is the main content of the last space. Below we continue to decompose figure 1, which says the first part of the second part, the second part is the Httpcontrollerdispatcher type to Apicontroller type of generation process, that is, figure 1.

First, our ASP. NET WEB API framework gets a controllerselector (Controller selector)from the Services container in Httpconfiguration. This controller selector is the corresponding type you can see from Figure 2, also shown in Figure 1, is very clear.

So what does controllerselector mainly do? Must be the choice of controller Ah, of course, according to the request to select the corresponding controller is the main function , what is the secondary function? The secondary function is to generate the controller cache, or from which to choose. In the ASP. NET MVC framework, the controller cache is present in the XML file, and it is now curious what kind of storage is in the controller cache in the ASP.

Let's take a look at the secondary features of the controller selector .

Controller Selector Minor Features

First we explain the cache type is concurrentdictionary<string, httpcontrollerdescriptor> type, is a one by one corresponding key value team, string represents the controller name, And Httpcontrollerdescriptor represents the controller description type of the controller, this type is very important later, we need to understand concurrentdictionary<string, The origin of the httpcontrollerdescriptor> cache.

First, when we instantiate the controller selector, the controller cache has been created in the constructor of the controller selector, and the detailed creation process can be seen in Figure 1. is loaded into the specified assembly by the Defaultassembliesresolver type (or by a work item that we define ourselves), and is referred to the Defaulthttpcontrollertyperesolver type by the ASP. The default search filter in the API framework returns all the qualified controller types (Controllertypes) loaded in the assembly to see a demo sample.

The project structure used is a demonstration sample of the last space:

Figure 3


Figure 4


In Figure 4 We define some additional controller types, and then define the following demo sample code on the Selfhost side, for example:

Code 1-1

        Staticvoidwritercontrollertypemessage (httpselfhostserverselfhostserver)        {             icollection<type>types =selfhostserver.configuration.services.gethttpcontrollertyperesolver (). Getcontrollertypes (SelfHostServer.Configuration.Services.GetAssembliesResolver ());            foreach (typetypeintypes)            {                Console.WriteLine (type. Namespace+ "_______" +type. Name);            }        }


And this static function is called at the end of the note:

Using (Httpselfhostserverselfhostserver=newhttpselfhostserver (selfhostconfiguration))            {                SelfHostServer.Configuration.Routes.MapHttpRoute (                    "Defaultapi", "Api/{controller}/{id}", new {id= Routeparameter.optional});                 SelfHostServer.Configuration.Services.Replace (typeof (Iassembliesresolver),                    Newcustomassembliesresolver.loadspecifiedassembliesresolver ());                  Writercontrollertypemessage (selfhostserver);                 Selfhostserver.openasync ();                Console.WriteLine ("Server-side service listener is turned on");                Console.read ();            }


Result 5:

Figure 5

After we get the controllertypes, there's an Httpcontrollertypecache type object in the ASP. Some of the previous operations were handled by the Httpcontrollertypecache type, and Httpcontrollertypecache had to do a very important job after acquiring the controllertypes. is to group the Controllertypes and finally return a dictionary<string, ilookup<string, type>> type of object, take the demo example above, After the last grouped dictionary<string, ilookup<string, the type>> type value should be:

Writer-->namespacecontrollerone->writercontroller

Namespacecontrollertwo->writercontroller

Read-->namespacecontrollerone->readcontroller

Writerandread-->namespacecontrollerthree->writerandreadcontroller

Product-->webapicontroller->productcontroller

The value at this time is not the last cache type, but the dictionary<string,ilookup<string generated by our controller selector According to the Httpcontrollertypecache type. Type>> type value to generate concurrentdictionary<string, httpcontrollerdescriptor> cache type, or based on the demo sample above, let's take a look at the last generated cache type value.

Change 1-1 For example the following demo sample code:

Code 1-2

Staticvoidwritercontrollertypemessage (httpselfhostserverselfhostserver) {icollection<type>types= SelfHostServer.Configuration.Services.GetHttpControllerTypeResolver ().            Getcontrollertypes (SelfHostServer.Configuration.Services.GetAssembliesResolver ()); foreach (Typetypeintypes) {Console.WriteLine (type. Namespace+ "_______" +type.            Name); }//dictionary<string,ilookup<string, type>> controllertypecache = types. Groupby<type,string> (t = t.name,stringcomparer.ordinalignorecase).             Todictionary<igrouping<string,type>, string, ilookup<string, type>>//(g = G.key, g = g.tolookup<type,string> (t = (t.namespace. String).             Empty), stringcomparer.ordinalignorecase), stringcomparer.ordinalignorecase); foreach (var value in Controllertypecache)//{//foreach (var val in value.         Value)   {//}//} idictionary<string, Httpcontrollerdescriptor >mapping=selfhostserver.configuration.services.gethttpcontrollerselector ().             Getcontrollermapping (); foreach (varmeginmapping) {Console.WriteLine ("Controllername:" +meg. Key+ ". Controllertypename: "+meg.            Value.ControllerType.Name); }         }


Result 6:

Figure 6


(The part that you stare at in code 1-2 is the ability to see the values of the dictionary<string, ilookup<string, type>> types returned by grouping operations on Controllertypes.)

Controller Selector main function

After the secondary function is read, the main function presumably everyone is also very clear, after the controller cache object, the controller selector will be based on the Httprequestmessage object in the routing data object to obtain the controller name, The corresponding Httpcontrollerdescriptor type instance is then fetched from the cache.

Detailed Build work

The work of generating ihttpcontroller after obtaining an instance of the Httpcontrollerdescriptor type becomes very easy, or from the Services container in the httpconfiguration to obtain the corresponding work item responsible for controller generation activation, in Figure 1 can be clearly seen in the Defaulthttpcontrolleractivator type, When the Defaulthttpcontrolleractivator type is working, it gets the appropriate container for the Dependencyresolver property from the Httpconfiguration. It is assumed that the situation here is not sufficient to invoke the subsequent typeactivator to generate the activation Ihttpcontroller (through reflection).


Jinyuan

Source: http://blog.csdn.net/jinyuan0829

This article is copyrighted by the author and Csdn co-owned, welcome reprint, but without the author's permission must retain this paragraph, and on the article page

ASP. NET WEB API Controller creation process (ii)

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.