What is the correct pattern to implement long running background work in Asp.Net Core?
To implement long-running background work in ASP.NET Core, the recommended pattern is to use hosted services. Hosted services are classes that implement the IHostedService
interface, which provides methods for starting and stopping background tasks. This approach ensures that the background tasks are managed by the ASP.NET Core runtime, allowing for proper initialization, execution, and graceful shutdown of these tasks.
IHostedService Interface:
The IHostedService
interface defines two methods:
StartAsync(CancellationToken cancellationToken)
: This method contains the logic to start the background task and is called when the application starts.StopAsync(CancellationToken cancellationToken)
: This method contains the logic to stop the background task and is called when the application is shutting down.BackgroundService Class:
ASP.NET Core provides an abstract BackgroundService
class that implements IHostedService
and provides a convenient way to create long-running background tasks. You only need to override the ExecuteAsync
method to define the background task logic.
Dependency Injection:
Background services can use dependency injection to access other services within the application. However, only transient or singleton services can be directly injected into the constructor of a hosted service. Scoped services must be resolved within the ExecuteAsync
method using a service scope.
Here is an example of implementing a background service using the BackgroundService
class:
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
public class ExampleBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<ExampleBackgroundService> _logger;
public ExampleBackgroundService(IServiceProvider serviceProvider, ILogger<ExampleBackgroundService> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Background service is starting.");
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceProvider.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Perform your background task here
await dbContext.SomeLongRunningTaskAsync(stoppingToken);
}
_logger.LogInformation("Background service is running.");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
_logger.LogInformation("Background service is stopping.");
}
}
To register the background service, add it to the service collection in the Program.cs
or Startup.cs
file:
public class Program
{
public static void Main(string[] args)
{
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào