Registering hosted services in your WebHost or Host Let’s drill down further on the
IHostedService
interface since its usage is pretty similar in a
WebHost
or in a
Host
.
SignalR is one example of an artifact using hosted services, but you can also use it for much simpler
things like:
•
A background task polling a database looking for changes.
•
A scheduled task updating some cache periodically.
•
An implementation of QueueBackgroundWorkItem that allows a task to be executed on a
background thread.
•
Processing messages from a message queue in the background of a web app while sharing
common services such as
ILogger
.
•
A background task started with
Task.Run()
.
You can basically offload any of those actions to a background task that implements
IHostedService
.
The way you add one or multiple
IHostedServices
into your
WebHost
or
Host
is by registering them
up through the
AddHostedService
extension method in an ASP.NET Core
WebHost
(or in a
Host
in
.NET Core 2.1 and above). Basically, you have to register the hosted services within application startup
in
Program.cs .
//Other DI registrations;
// Register Hosted Services
builder.
Services
.
AddHostedService
();
builder.
Services
.
AddHostedService
();
builder.
Services
.
AddHostedService
();
//...
In that code, the
GracePeriodManagerService
hosted service is real code from the Ordering business
microservice in eShopOnContainers, while the other two are just two additional samples.
The
IHostedService
background task execution is coordinated with the lifetime of the application
(host or microservice, for that matter). You register tasks when the application starts and you have the
opportunity to do some graceful action or clean-up when the application is shutting down.
Without using
IHostedService
, you could always start a background thread to run any task. The
difference is precisely at the app’s shutdown time when that thread would simply be killed without
having the opportunity to run graceful clean-up actions.