160
CHAPTER 5 | Designing and Developing Multi-Container and Microservice-Based .NET Applications
As you can imagine, you can create multiple implementations of IHostedService and register each of
them in
Program.cs
, as shown previously. All those hosted services will be started and stopped along
with the application/microservice.
As a developer, you are responsible for handling the stopping action of your services when
StopAsync()
method is triggered by the host.
Implementing IHostedService with a custom hosted service class
deriving from the BackgroundService base class
You could go ahead and create your custom hosted service class from scratch and implement the
IHostedService
, as you need to do when using .NET Core 2.0 and later.
However, since most background tasks will have similar needs in regard to the cancellation tokens
management and other typical operations, there is a convenient abstract base class you can derive
from, named
BackgroundService
(available since .NET Core 2.1).
That class provides the main work needed to set up the background task.
The next code is the abstract BackgroundService base class as implemented in .NET.
// Copyright (c) .NET Foundation. Licensed under the Apache License, Version 2.0.
///
/// Base class for implementing a long running
cref=
"IHostedService"
/>
.
///
Dostları ilə paylaş: