Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to start a BackgroundService in ASP.NET Core

I have implemented a BackgroundService in an ASP.NET Core 2.1 application:

public class MyBackgroundService : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (true)
        {
            await DoSomethingAsync();
            await Task.Delay(10 * 1000);
        }
        return Task.CompletedTask;
    }
}

I have registered it in my ConfigureServices() method:

services.AddSingleton<MyBackgroundService>();

I am currently (reluctantly) starting it by calling (and not awaiting) the StartAsync() method from within the Configure() method:

app.ApplicationServices.GetService<SummaryCache>().StartAsync(new CancellationToken());

What is the best practice method for starting the long running service?

like image 343
Creyke Avatar asked Oct 19 '18 09:10

Creyke


People also ask

What is background service in .NET Core?

BackgroundService is a base class for implementing a long running IHostedService. ExecuteAsync(CancellationToken) is called to run the background service. The implementation returns a Task that represents the entire lifetime of the background service.

How do you call a background task with hosted service from .NET Core Web API?

In ASP.Net core, we can implement IHostedService interface to run background tasks asynchronously inside our application. It provides to two methods “StartAsync” and “StopAsync”. as the name suggested these methods is used to start and stop the task.

What is background jobs C#?

A background job is a class that implements the IBackgroundJob<TArgs> interface or derives from the BackgroundJob<TArgs> class. TArgs is a simple plain C# class to store the job data. This example is used to send emails in background.

How do I create a .NET Core?

Open Visual Studio 2019 and click on Create a new project, as shown below. The "Create a new project" dialog box includes different . NET Core 3.0 application templates. Each will create predefined project files and folders depends on the application type.


1 Answers

Explicitly calling StartAsync is not needed.

Calling

services.AddSingleton<MyBackgroundService>();

won't work since all service implementations are resolved via DI through IHostedService interface. edit: e.g. svcProvider.GetServices<IHostedService>() -> IEnumerable<IHostedService>

You need to call either:

services.AddSingleton<IHostedService, MyBackgroundService>();

or

services.AddHostedService<MyBackgroundService>();

edit: AddHostedService also registers an IHostedService: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionhostedserviceextensions.addhostedservice?view=aspnetcore-2.2

like image 94
Cosmin Sontu Avatar answered Oct 16 '22 11:10

Cosmin Sontu