19.11.2022 Views

NET-Microservices-Architecture-for-Containerized-NET-Applications

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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 the familiar

ConfigureServices() method of the Startup class, as in the following code from a typical ASP.NET

WebHost.

public IServiceProvider ConfigureServices(IServiceCollection services)

{

//Other DI registrations;

}

// Register Hosted Services

services.AddHostedService<GracePeriodManagerService>();

services.AddHostedService<MyHostedServiceB>();

services.AddHostedService<MyHostedServiceC>();

//...

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.

The IHostedService interface

When you register an IHostedService, .NET will call the StartAsync() and StopAsync() methods of

your IHostedService type during application start and stop respectively. For more details, refer

IHostedService interface

As you can imagine, you can create multiple implementations of IHostedService and register them at

the ConfigureService() method into the DI container, as shown previously. All those hosted services

will be started and stopped along with the application/microservice.

159 CHAPTER 5 | Designing and Developing Multi-Container and Microservice-Based .NET Applications

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!