NET Core 2.1 new features generic host (Universal host)

Source: Internet
Author: User
Tags hosting webhost

ASP. NET Core 2.1 new features generic host (Universal host), learn about https://www.cnblogs.com/CoderAyu/p/9564977.html

What is generic Host?
Image

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

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

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.

https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/

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.

Https://github.com/liuzhenyulive/Generic-Host-Demo

Generic host vs. Web Host
First, we open the download of the official demo, into the main function.

Image

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)
Configureappconfiguration
(Used to configure configuration) Webhost also has this method, but everyone by default may not be called.
Image
Configureservices
(for configuring service, that is, dependency injection) Webhost actually has a configureservices method that can be called.
Image
However, we rarely use this, usually in the startup Configureservices method for dependency injection.
Configurelogging
(The configuration required for this application, not required) webhost still there!
Image
Builder. Runconsoleasync ()
Image
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!

There is a WEB host for the Universal host (Generic hosts).
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 to use?
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.

Copy Code
Public async Task Startasync (cancellationtoken cancellationtoken = Default (CancellationToken))
{
This._logger. Starting ();
TaskCompletionSourceCompletionSource1 = new TaskCompletionSource();

  ref CancellationToken local = ref cancellationtoken;  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 = iapplicationlifetime)?.  Stopapplication ()), (object) applicationlifetime);  Object task = await completionsource1.task; 

This._hostedservices = this. Services.getservice<ienumerable > (); foreach (Ihostedservice hostedservice in this._hostedservices) await Ho Stedservice.startasync (CancellationToken). Configureawait (False
);

  this._applicationLifetime?.NotifyStarted();  this._logger.Started();}

Copy Code

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 > ();

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? Laugh loudly

The steps I summarize are as follows:

The

Customizes a service that inherits the Ihostedservice interface. The
implements the Startasync method of Ihostedservice and puts the tasks that need to be performed into this method. The
registers the service in the IOC container (servicecollection).
to run a custom task
for steps 1 and 2, the corresponding code is as follows:
Copy Code
public class Printtexttoconsoleservice:ihostedservice, IDisposable
{
Private readonly ILogger _logger;
Private ReadOnly ioptions _appconfig;
Private Timer _timer;

    public PrintTextToConsoleService(ILogger<PrintTextToConsoleService> logger, IOptions<AppConfig> appConfig)    {        _logger = logger;        _appConfig = appConfig;    }    public Task StartAsync(CancellationToken cancellationToken)    {        _logger.LogInformation("Starting");        _timer = new Timer(DoWork, null, TimeSpan.Zero,            TimeSpan.FromSeconds(5));        return Task.CompletedTask;    }    private void DoWork(object state)    {        _logger.LogInformation($"Background work with text: {_appConfig.Value.TextToPrint}");    }    public Task StopAsync(CancellationToken cancellationToken)    {        _logger.LogInformation("Stopping.");        _timer?.Change(Timeout.Infinite, 0);        return Task.CompletedTask;    }    public void Dispose()    {        _timer?.Dispose();    }}

Copy Code
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.

Image

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

For step 3, the corresponding code is as follows
Copy Code
public static async Task Main (string[] args)
{
var builder = new Hostbuilder ()//instantiation of a common host
. Configureappconfiguration ((hostingcontext, config) =
{
Config. Addjsonfile ("Appsettings.json", optional:true);
Config. Addenvironmentvariables ();

                if (args != null)                {                    config.AddCommandLine(args);                }            }) //配置Configuration            .ConfigureServices((hostContext, services) =>            {                services.AddOptions();                services.Configure<AppConfig>(hostContext.Configuration.GetSection("AppConfig"));                services.AddSingleton

<ihostedservice, printtexttoconsoleservice>
();
})//Configure 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();    //在控制台应用程序中运行通用主机    }

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

F5 Run
Image

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

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1

NET Core 2.1 new features generic host (Universal host)

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.