Adding a hosted service to an ASP.NET Core app

Hosted services are a great way of running background tasks.

They can be added in ASP.NET Core, or they can be set up in their own separate project.

Watch our tutorial to see how a .NET hosted service works:

We have this hosted service:

public class MyBackgroundService : BackgroundService
	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
		await Task.CompletedTask;

And here is the Program.cs file that we have for our ASP.NET Core application.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();


How would we add the hosted service to the configuration in Program.cs?