gpt4 book ai didi

c# - DbContext 实例同时在两个地方使用 - EF - Hangfire

转载 作者:行者123 更新时间:2023-12-04 04:05:53 24 4
gpt4 key购买 nike

我正在使用 EF Core 和 Hangfire运行重复性作业。 Hangfire 似乎导致了以下错误:

A second operation started on this context before a previous operationcompleted. This is usually caused by different threads using the sameinstance of DbContext. For more information on how to avoid threadingissues with DbContext

而且..我不确定为什么。我按如下方式注册 EF 上下文:

services 
.AddDbContext<PaymentContext>(options => options.UseNpgsql(connectionString),
ServiceLifetime.Transient);

然后..

app.UseHangfireDashboard();
app.UseHangfireServer();

RecurringJob.AddOrUpdate(() => myService.ExecuteMyJob(), Cron.Minutely);

其中 myService 已注入(inject) Startup.Configure 函数,并且 myService 包含对 DbContext 的引用。这在理论上是暂时的,因此不应由服务和其他地方共享。

但是堆栈跟踪引导到这里:

var plans = _context.Plan
.Include(pp => pp.PlanItem)
.Where(pp => pp.PolicyId == policyId)
.ToList() // materialise query
.OrderBy(pp => pp.PlanItem.First().Date)
.ToList();

最佳答案

您应该为您的依赖创建作用域。

public class Job
{
private readonly IServiceProvider _serviceProvider;

public Job(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public void ExecuteJob()
{
using (var scope = serviceProvider.CreateScope())
{
var databaseContext = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
// do something
}
}
}

关于c# - DbContext 实例同时在两个地方使用 - EF - Hangfire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62520368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com