ASP. NET Core 2.1 new features generic host (universal host), see

Source: Internet
Author: User
What is generic Host?

This is a new host added to ASP. 2.1 Version of ASP. NET core, there are two available host.

    • Web host – host for hosting web programs is the common webhost that we are familiar with in the MAI function of an ASP. NET core application, created with Createwebhostbuilder.

    • Generic Host (Available in ASP. NET Core 2.1) – for hosting non-Web apps (for example, apps that run background tasks). In a future release, a generic host will be available for hosting any type of app, including Web apps. The common host will eventually replace the WEB host, which is probably the reason this type of host is called a universal host, in this blog, we will combine the source code to discuss how the common host works.
Why use a generic host?

The universal host allows me to simplify the creation of console applications (personal insights) with the idea of writing ASP. NET core (e.g., control inversion, Dependency injection, IOC container), host responsible for program initiation and life cycle management, This is useful for applications that do not handle HTTP requests (Web applications that handle HTTP requests, hosted by web host), and the goal of the universal host is to detach the HTTP pipeline from the web host, making the same thing as the ASP for the other. Net Core. Core program.

Demo download

Before starting to follow my analysis of the universal host, you can download this official demo on GitHub.

If you feel that downloading a whole is slow, can be downloaded from my GitHub repository, there is no other content, domestic github is slower, if you download from the official that warehouse may take a long time or even fail.

Generic host vs. Web Host

First, we open the download of the official demo, into the main function.

As you can see, this is simply a lite ASP. NET core application, and for all the methods that appear in this main function, you are familiar with the ASP. NET core Web application, so I made a comparison with the webhost of ASP. To help you find the feeling.

Universal Host Web Host
New Hostbuilder () Webhost.createdefaultbuilder (args)
(Used to configure configuration)
Webhost also has this method, but everyone by default may not be called.
(for configuring service, that is, dependency injection)
Webhost actually has a configureservices method that can be called.

However, we rarely use this, usually in the startup Configureservices method for dependency injection.
(Required configuration for this application, not required)
Webhost is still there!
Builder. Runconsoleasync ()

The Runconsoleasync is actually a hostbuilder.
Builder then run
Createwebhostbuilder (args). Build (). Run ();

This is the build () in the main function. Run ();

No no no no no
The Configure () method in startup
ASP. NET core configuration for HTTP request pipeline in this method

In contrast, I have done the following summary!

    1. There is a WEB host for the Universal host (Generic hosts).
    2. The HTTP pipeline of Web host, or Startup.configure (), is not in the generic host.

This should be the beginning: The goal of the Universal host is to detach the HTTP pipeline from the web host, making the same set of ASP. Net core programs available to other.

How do I use it? Interpretation of the Run function

I think we need to know how to use it, so let's start by knowing what the host is doing inside the Run method.

So we go deep into the source, all the way f12!

Builder. Runconsoleasync (); =>hostbuilder.useconsolelifetime (). Build (). RunAsync (cancellationtoken); = = await host. Startasync (token);

Finally found, the most critical here.

 Public AsyncTask Startasync (CancellationToken cancellationtoken =default(CancellationToken)) {       This. _logger.      Starting (); TaskCompletionSource<Object> CompletionSource1 =Newtaskcompletionsource<Object>(); refCancellationToken local =refCancellationToken; TaskCompletionSource<Object> CompletionSource2 =CompletionSource1; Local. Register (Action<Object>) (obj = (taskcompletionsource<Object>) (obj). Trysetcanceled ()), (Object) completionSource2); Ihostlifetime hostLifetime1= This. _hostlifetime; TaskCompletionSource<Object> CompletionSource3 =CompletionSource1; Hostlifetime1.registerdelaystartcallback (Action<Object>) (obj = (taskcompletionsource<Object>) (obj). Trysetresult ((Object)NULL)), (Object) completionSource3); Ihostlifetime hostLifetime2= This. _hostlifetime; Applicationlifetime Applicationlifetime= This. _applicationlifetime; Hostlifetime2.registerstopcallback (Action<Object>) (obj = (obj asiapplicationlifetime)?. Stopapplication ()), (Object) applicationlifetime); ObjectTask =awaitCompletionsource1.task; 
This . _hostedservices = this. Services.getservice<ienumerable<ihostedservice>> (); foreach (Ihostedservice hostedservice in this . _hostedservices) await Hostedservice.startasync (CancellationToken). Configureawait (false
);       this. _applicationlifetime? . Notifystarted ();        This . _logger. Started ();    }

Know that everyone likes yellow color, so I use yellow to put the most critical code out, then what is the meaning of the code?

This._hostedservices = this. Services.getservice<ienumerable<ihostedservice>> ();

This line means that all services that implement the Ihostedservice are removed from the container.

This means that after we have implemented the Ihostedservice, we need to register the service with the IOC container.

foreach (Ihostedservice hostedservice in this._hostedservices)
Await Hostedservice.startasync (CancellationToken). Configureawait (FALSE);

Executes the Startasync method for each service.

So, do you know how to use it?

The steps I summarize are as follows:

    1. Customize a service that inherits the Ihostedservice interface.
    2. Implement the Ihostedservice Startasync method and put the tasks that need to be performed into this method.
    3. Register the service in the IOC container (servicecollection).
The custom task runs for steps 1 and 2, and the corresponding code is as follows:
 Public classPrinttexttoconsoleservice:ihostedservice, IDisposable {Private ReadOnlyILogger _logger; Private ReadOnlyIoptions<appconfig>_appconfig; PrivateTimer _timer;  PublicPrinttexttoconsoleservice (ilogger<printtexttoconsoleservice> logger, ioptions<appconfig>appConfig) {_logger=logger; _appconfig=AppConfig; }         PublicTask Startasync (CancellationToken cancellationtoken) {_logger. Loginformation ("starting"); _timer=NewTimer (DoWork,NULL, TimeSpan.Zero, Timespan.fromseconds (5)); returnTask.completedtask; }        Private voidDoWork (ObjectState ) {_logger. Loginformation ($"Background Work with text: {_appconfig.value.texttoprint}"); }         PublicTask Stopasync (CancellationToken cancellationtoken) {_logger. Loginformation ("stopping."); _timer?. Change (Timeout.infinite,0); returnTask.completedtask; }         Public voidDispose () {_timer?.        Dispose (); }    }

As you can see, in Startasync, a timed task is defined, with a timed task that executes the DoWork method every five seconds.

In the DoWork method, the Logger logs a section of content.

Because in the main method, the log is configured as follows.

So, once the log is logged, the content is output in the console.

For step 3, the corresponding code is as follows
 Public Static AsyncTask Main (string[] args) {            varBuilder =NewHostbuilder ()//instantiate a generic host. Configureappconfiguration ((hostingcontext, config) ={config. Addjsonfile ("Appsettings.json", Optional:true); Config.                    Addenvironmentvariables (); if(Args! =NULL) {config.                    Addcommandline (args); }                }) //Configuring the Configuration. Configureservices (hostcontext, services) ={Services.                    AddOptions (); Services. Configure<AppConfig> (HostContext.Configuration.GetSection ("AppConfig")); Services. Addsingleton 
<ihostedservice, printtexttoconsoleservice>
();                })     // Configure the Service (Dependency injection)                . Configurelogging (hostingcontext, logging) = {                    logging. Addconfiguration (hostingContext.Configuration.GetSection ("Logging"));                    Logging. Addconsole ();                });    // Configure log (this project will use log to output the content in the console)            await Builder. Runconsoleasync ();    // running a universal host in a console application        }

The yellow section registers the Printtexttoconsoleservice that implement the Ihostedservice interface in the container.

F5 Run

As you can see, in the console, there is a content output every five seconds, which means that the DoWork method has not been executed for five seconds, indicating that Printtexttoconsoleservice's Startasync was successfully invoked.

I hope this article will help you understand the common host can help, if the. Net Core source code analysis, the trend of new technology interested

Welcome to follow me

Not regularly launched practical work, thank you!

Reference documents

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: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: