简体   繁体   English

添加每 7 天删除一次数据的后台服务

[英]Adding a background service that deletes data every 7 days

I have a class Issue which contains some information including their dates.我有一个 class Issue ,其中包含一些信息,包括它们的日期。 I would like to create a background service that deletes data older than 7 days from the the database.我想创建一个后台服务,从数据库中删除超过 7 天的数据。

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我已经在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'.)' System.AggregateException:'无法构建某些服务(验证服务描述符'ServiceType:Microsoft.Extensions.Hosting.IHostedService Lifetime:Singleton ImplementationType:BackgroundWorker'时出错:无法使用来自singleton的范围服务'APIExample.AppDbContext' Microsoft.Extensions.Hosting.IHostedService'.)'

You can not inject DbContext like this way, use ServiceScopeFactory你不能像这样注入 DbContext,使用 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;
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM