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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With