Layim.aspnetcore Middleware Development Diary (ii) introduction of preparatory knowledge

Source: Internet
Author: User

Objective

Developing a Aspnetcore middleware requires an understanding of requestdelegate. In addition, you need to understand the dependency injection in . NET Core . Another is access to embedded resources. For example: The use ofEmbeddedfileprovider . So this article on these three points to do a simple introduction. It's not difficult to understand these things so that they are basically developed.

Requestdelegate

For Requestdelegate 's introduction, we can look at this article: https://www.cnblogs.com/artech/p/inside-asp-net-core-pipeline-01.html.

I'll simply pass through the code here, here's an example of a simple HelloWorld.

  

namespacelayim.aspnetcore.webdemo.middleware{ Public classHelloworldmiddleware {Private ReadOnlyrequestdelegate Next;  PublicHelloworldmiddleware (requestdelegate next) { This. Next =Next; }         Public AsyncTask Invoke (HttpContext context) {awaitContext. Response.writeasync ("Hello World"); }    }     Public Static classhelloworldextensions { Public Static voidUsehelloworld (iapplicationbuilder builder) {Builder. Usemiddleware<HelloWorldMiddleWare>(); }    }}

Then register this middleware in Iapplicationbuilder in startup. Just like the app. USEMVC () .

 Public void Configure (Iapplicationbuilder app, ihostingenvironment env)        {            app. Usehelloworld ();         }

Look at the effect of the operation:

So this is the use of requestdelegate , then we can see that there is a type of requestdelegate in the helloworldmiddleware Next variable. This allows the call chain to be concatenated together. We can do some global work through requestdelegate , such as request verification, screening, logging, statistics and so on, to see the demand. Then choose whether or not to perform next according to the situation . Invoke (context) method to go down the request process until all processes have been completed or to a process that has been intercepted. In the same way, the request to start with {/layim} was intercepted in Layim.aspnetcore . Otherwise, continue to execute other business logic. The sample code is as follows:

if false )     {         await next? Invoke (context);          return ;     }

Although not annotated, it can be seen whether the request is Layim, if not, skip directly.

Dependencyinjection

Dependency Injection I believe that everyone is familiar with, to say that he has any advantage, the most intuitive one of the benefits is decoupling. In the previous layim_netclient project, I put the implementation of the cloud into the middleware directly, this is the coupling is too high. If users don't want to use the cloud, they can't use it. Then in the Layim.aspnetcore project, by using the method of dependency injection, the core interface is separated from the implementation class, so that the new implementation class can be transformed without changing the core code. Here I directly use the examples in the project as an introduction:

When initializing the middleware , the system will automatically inject IServiceProvider into the middleware

 Public Layimmiddleware (requestdelegate Next, layimoptions options,iserviceprovider serviceprovider)        {            this. Next = next;              this. options = options;             this. serviceprovider = serviceprovider;            Layimservicelocator.setserviceprovider (this. serviceprovider);        }

I use layimservicelocator to save an instance of IServiceProvider , then when it is used. Through it we can get the service we want. Here is an example of getting tokens. The following methods are defined in the ilayimserver interface:

Tokenresult GetToken (string userId);

The method is then implemented in the new Rongcloud project, and the extension iservicecollection

  Public classRongcloudserver:ilayimserver {Private ReadOnlyrongcloudconfig config;  Publicrongcloudserver (rongcloudconfig config) { This. config =config; }         PublicTokenresult GetToken (stringuserId) {            return NewTokenresult {Code=0, msg="OK", token="123456"            }; }    }
 Public Static void Addlayim ( This iservicecollection services, rongcloudconfig config)        {            services. Addsingleton (config);            Services. Addsingleton<ilayimserver, rongcloudserver>();        }

So, in the demo we can use this:

 Public void configureservices (iservicecollection services)        {            services. Addmvc ();                 = =                {"123456";                 " 654321 " ;            });        }    

Here, if you do not want to use the cloud communication, you can implement the Ilayimserver interface, and then do their own expansion.

The core side depends on the interface, the processing logic is as follows: (other code can be ignored, temporarily see the middle two lines of code)

// Get token  to connect WebSocket Routes. Addquerycommand ("/token", context = =    {var server = Layimservicelocator.getservice<ilayimserver>();     return server. GetToken (context. request.query["uid");  });

As you can see, the ilayimserver interface is obtained by Servicelocator , and then the interface method is called. This achieves the purpose of decoupling the framework code from the implementation code. Let's look at the effect:

  

The code works fine, and here is not a demonstration of other implementations. If you do not understand the small partners can go to download code debugging, or direct messages I can.

Embeddedfileprovider

Good text recommendation: https://www.cnblogs.com/artech/p/net-core-file-provider-04.html

You know, as Swaggerui, why do we have access to the UI interface when we configure it? Where is his resource file? In fact, this is the role of embedded resources. For those of you who want to get to know more, I'll simply describe how to implement access to embedded resources.

In fact, it is very simple, the following code is done:

  App. Usefileserver (new  fileserveroptions            {                = options. Apiprefix,                New embeddedfileprovider (assembly, "namespace"),            });

As you can see,fileprovider is a embeddedfileproviderwith two parameters passed in, one for the assembly and one for the static resource namespace.

However, when we add a static file, it is important to note that the file Generation Action property is set to an embedded resource, otherwise it cannot be accessed. (But there are also practices for using configuration files)

So, let's visit the static resources, the effect is as follows:

  

Then dynamic and static resources are accessible, so we can work on the next step.

Summarize

This paper briefly introduces the basic knowledge and usage of middleware, access to embedded resources and simple use of dependency injection, because it is used in the subsequent development process.

Blog trailer:Layim.aspnetcore Middleware Development Diary (iii) basic framework construction

  Project Address:Https://github.com/fanpan26/LayIM.AspNetCore (This code corresponds to BLOG2 Branch) Welcome Small Partners Star onlookers comments.

Layim.aspnetcore Middleware Development Diary (ii) introduction of preparatory knowledge

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.