Asp.netweb API Controller creation process (ii)

Source: Internet
Author: User

ASP. NET Web API Controller creation Process ( two )

Objective

Originally this essay should be written out last week, because the body can not keep up with the rhythm of the cold fever powerless, this weather cold fever life than death, also really experience what is called sick to 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 ASP. NET Web API controller creation process, before the next chapter, I will review the contents of the previous article, and in this article to integrate, let us see is an entire creation process.

ASP. NET Web API controller creation, activation process

l ASP. NET Web API Controller creation Process ( i )

l ASP. NET Web API Controller creation Process ( two )

Create, activate process

Figure 1

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/46/43/wKioL1PxUgnw1q5JAAO-J5o25OE377.jpg "title=" Controller1.png "width=" 738 "height=" 332 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:738px;height:332px; "alt=" Wkiol1pxugnw1q5jaao-j5o25oe377.jpg "/>

in the previous space, we said Apicontroller is created by the Httpcontrollerdispatcher type, which is just on the surface, and figure 1 shows the whole process of controller creation, let's go back to the previous article about , otherwise it will feel incoherent, in the review will also be on the figure 1 is explained.

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

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/46/41/wKiom1PxUQ6BxiG-AAF_rzY-DJ8987.jpg "title=" Controller2.png "alt=" Wkiom1pxuq6bxig-aaf_rzy-dj8987.jpg "/>

Let's just explain. Httpconfiguration section, there are two properties in the Httpconfiguration type, the first of which is the Servicescontainer type of property Services , the second one is Properties 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 angle is an IoC container that relies on injection into the httpconfiguration , for The Dependencyresolver attribute is pretty much what it means.

just Most of the Services that are stored in this container are 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 custom work items:

SelfHostServer.Configuration.Services.Replace (typeof (Iassembliesresolver), NEWCUSTOMASSEMBLIESRESOLVER.L Oadspecifiedassembliesresolver ());

The default defaultassembliesresolver type can be seen here in Figure 2 to perform this work.

This is the main content of the last space. Let's continue with the decomposition of Figure 1, which says the first part of the second part, the second part is the Httpcontrollerdispatcher type to Apicontroller The type generation process, which is Figure 1 .

first of all, our The ASP. NET Web API framework gets a controllerselector from the Services container in Httpconfiguration (Controller selector) , this controller selector corresponds to the 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 choose the appropriate 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, where the controller cache exists in an XML file, it is now curious What kind of storage is in the controller cache in the ASP.

let's just take a look. Controller Selector the secondary function .

Controller Selector Minor Features

let's start by explaining that 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 corresponding controller, this type is very important later on, we need to understand concurrentdictionary<string first , The origin of the httpcontrollerdescriptor> cache.

first, when our controller selector is instantiated, the controller cache has been created in the constructor of the controller selector using the lazy load technique , which can be seen in Figure 1 , by The Defaultassembliesresolver type (or our custom work item) loads the specified assembly and is referred to the defaulthttpcontrollertyperesolver type according to the The default search filters in the ASP. NET Web API Framework return all of the eligible controller types (controllertypes) in the load assemblyto see an example.

The project structure used is also an example of the last space:

Figure 3

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/46/41/wKiom1PxUVPDFd0SAAB4Da14LAw080.jpg "title=" Controller3.png "alt=" Wkiom1pxuvpdfd0saab4da14law080.jpg "/>

Figure 4

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/46/41/wKiom1PxUV2z2LplAAFRhEA66TI760.jpg "title=" Controller4.png "alt=" Wkiom1pxuv2z2lplaafrhea66ti760.jpg "/>

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

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 on the registration side:

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

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/46/41/wKiom1PxUXXDmUPEAAEjcnAu8us361.jpg "title=" Controller5.png "alt=" Wkiom1pxuxxdmupeaaejcnau8us361.jpg "/>

in our acquisition of after Controllertypes,there is an object of type Httpcontrollertypecache in the ASP. NET Web API framework , and some of the previous operations were Httpcontrollertypecache type to deal with, and after Httpcontrollertypecache acquired the controllertypes to do a very important work, is to group the controllertypes and finally return an object of dictionary<string, ilookup<string, type>> type, Take the 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 final cache type, but rather the dictionary<string generated by our controller selector based on the Httpcontrollertypecache type . ilookup<string, type>> type value to generate concurrentdictionary<string, httpcontrollerdescriptor> Cache type, or based on the example above, let's take a look at the last generated cache type value.

The following example code is modified 1-1:

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&NBsp;=> 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

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/46/41/wKiom1PxUYzjIU-aAAGVFu9zCOw938.jpg "title=" Controller6.png "alt=" Wkiom1pxuyzjiu-aaagvfu9zcow938.jpg "/>

(The part that is commented out in code 1-2 is that you can view the group operations for Controllertypes return dictionary<string, ilookup<string, the value of the type>> type).

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 routing data object in the Httprequestmessage object gets the controller name and then gets the corresponding httpcontrollerdescriptor type instance from the cache .

Specific build work

in the acquisition of the Httpcontrollerdescriptor Type instance after the generation of Ihttpcontroller work becomes very simple, or from the httpconfiguration The Services container obtains the corresponding work item responsible for controller generation activation, which can be clearly seen in Figure 1 as the Defaulthttpcontrolleractivator type, The Defaulthttpcontrolleractivator type works when it gets the container corresponding to the Dependencyresolver property from the Httpconfiguration. If the situation here is not satisfied, then the subsequent typeactivator will be called to generate the activation Ihttpcontroller ( through reflection ).




This article is from the "Jinyuan" blog, be sure to keep this source http://jinyuan.blog.51cto.com/8854733/1541436

Related Article

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.