I have a class Issue
which contains some information including their dates. I would like to create a background service that deletes data older than 7 days from the the database.
Here is the code I have tried:
using APIExample;
using Microsoft.Identity.Client;
public class BackgroundWorker : BackgroundService
{
private readonly AppDbContext _appDbContext;
public BackgroundWorker(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_appDbContext.Issue.RemoveRange(_appDbContext.Issue.Where(a => (a.Created.AddDays(7) >= DateTime.Now)));
_appDbContext.SaveChanges();
return Task.CompletedTask;
}
}
I have injected this in the program.cs
class
builder.Services.AddHostedService<BackgroundWorker>();
This is the error I am getting:
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: BackgroundWorker': Cannot consume scoped service 'APIExample.AppDbContext' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.)'
You can not inject DbContext like this way, use ServiceScopeFactory
public class BackgroundWorker : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public BackgroundWorker(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var _appDbContext= scope.ServiceProvider.GetService<AppDbContext>();
_appDbContext.Issue.RemoveRange(_appDbContext.Issue.Where(a => (a.Created.AddDays(7) >= DateTime.Now)));
_appDbContext.SaveChanges();
return Task.CompletedTask;
}
}
}