The previous article introduces .Net coreConfiguration of general host, After the basic configuration is completed, the next step is to register our background tasks. .net core provides a common backend service interface IHostedService, called hosting services. An example of registering a hosting service is as follows:
((hostContext, services) => { <LifetimeEventsHostedService>(); <TimedHostedService>(); });
And the simple implementation of a hosting service is as follows:
class MyHostedService :IHostedService { public Task StartAsync(CancellationToken cancellationToken) { return ; } public Task StopAsync(CancellationToken cancellationToken) { return ; } }
Each IHostedService implementation is executed in the order of service registration in ConfigureServices. StartAsync is called on each IHostedService when the host starts. When the host is shut down normally, StopAsync is called in reverse registration order. Compared with traditional backend tasks, this provides an advantage: it can be graceful close when the service is terminated.
In addition, because of the use of the DI framework, other services can be easily obtained in the constructor of the hosted service:
public MyHostedService(IHostEnvironment env, IHostApplicationLifetime appLifetime) { }
IHostingEnvironment
IHostingEnvironment is mainly used to provide App environment information, so I won't introduce it in detail.
IApplicationLifetime
IApplicationLifetime is a service that is often introduced by managed services. It allows to obtain application startup and shutdown events and can close the entire host. The specific interface is as follows:
Event subscription:
ApplicationStarted: The host is fully started.
ApplicationStopped: The host is completing normal shutdown. All requests should be processed. Close is blocked until this event is completed.
ApplicationStopping: The host is performing a normal shutdown. The request is still being processed. Close is blocked until this event is completed.
operate:
StopApplication: Close the entire host
BackgroundService
Many times, our background service is often just a simple task and does not need to be closed. At this time, we can use a simpler model: BackgroundService
class MyHostedService : BackgroundService { protected override Task ExecuteAsync(CancellationToken stoppingToken) { //do something return ; } }
It itself is an implementation of IHostedService, but it further simplifies the program functions and only provides an ExecuteAsync interface. We only need to implement background tasks in this function.
This is all about this article about Core universal hosting implementation of hosting services. I hope it will be helpful to everyone's learning and I hope everyone will support me more.