ASP. NET WEB API Controller creation process (ii)

Source: Internet
Author: User

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

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
    • ASP. NET Web API Controller creation Process ( i)
    • ASP. NET Web API Controller creation Process ( II)

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, we first review the previous article, otherwise we will feel incoherent, In retrospect, figure 1 is also 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

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 a dependency injection into the httpconfiguration of the IOC container, for the Dependencyresolver attribute is similar to this meaning.

However, 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 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),                    new Customassembliesresolver.loadspecifiedassembliesresolver ());

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 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 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 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 corresponding controller, this type is very important later, we need to understand concurrentdictionary<string, 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. is the Defaultassembliesresolver type (or our custom work item) that loads the specified assembly and is handed to the Defaulthttpcontrollertyperesolver type according to the ASP. The default search filter in the API framework returns all of the eligible controller types (controllertypes) in the loaded assembly, to see an example.

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

Figure 3

Figure 4

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

Code 1-1

        Static void writercontrollertypemessage (httpselfhostserver selfhostserver)        {            ICollection<Type> types =  SelfHostServer.Configuration.Services.GetHttpControllerTypeResolver (). Getcontrollertypes (SelfHostServer.Configuration.Services.GetAssembliesResolver ());             foreach inch types)            {                "_______" + type. Name);            }        }

And this static function is called on the registration side:

using(Httpselfhostserver selfhostserver =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 monitoring 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 above example, 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 according to 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

Static voidwritercontrollertypemessage (Httpselfhostserver selfhostserver) {ICollection<Type> types =SelfHostServer.Configuration.Services.GetHttpControllerTypeResolver ().            Getcontrollertypes (SelfHostServer.Configuration.Services.GetAssembliesResolver ()); foreach(Type typeinchtypes) {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(varMeginchmapping) {Console.WriteLine ("controllername:"+ Meg. Key +". Controllertypename:"+Meg.            Value.ControllerType.Name); }        }

Result 6:

Figure 6

(The part that you commented out in code 1-2 is that you can see the values for grouping operations on Controllertypes return dictionary<string, ilookup<string, type>> type).

Controller selector main function

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

Specific build work

The work of generating ihttpcontroller after obtaining an instance of the Httpcontrollerdescriptor type becomes very simple, 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 as the defaulthttpcontrolleractivator type, When the Defaulthttpcontrolleractivator type is working, 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).

Jinyuan

Source: http://www.cnblogs.com/jin-yuan/

This article is copyrighted by the author and the blog Park, welcome reprint, but without the consent of the author must retain this statement, and on the article page

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.