我得到"无法访问被处置对象"在调用使用DI注入的dbcontext(Transient-scoped)的方法期间的异常 - 很可能dbcontext在被调用时已经被释放。该方法由流畅的调度程序作为作业调用:
JobManager.AddJob(
() => ExecuteUpdateDbContext(),
(s) => s.ToRunNow().AndEvery(60).Minutes()
);
ExecuteUpdateDbContext方法适用于任何情况,除非由流畅的调度程序使用。我是否需要使用我的ExecuteUpdateDbContext方法执行一些特殊操作才能使其与流畅的调度程序一起使用?
答案 0 :(得分:0)
我在流畅的调度程序或其他同步功能上遇到了相同的问题。
为此,我创建了一个ServiceScopeFactory
对象,并将其注入注册表的构造函数中。
我在startup.cs的Configure()函数中初始化了我的作业管理器-
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
IServiceScopeFactory serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
JobManager.Initialize(new SchedulerRegistry(serviceScopeFactory));
}
SchedulerRegistry-
public SchedulerRegistry(IServiceScopeFactory serviceScopeFactory)
{
Schedule(() => new SyncUpJob(serviceScopeFactory)).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
}
SyncupJob-
public class SyncUpJob : IJob
{
/// <summary>
///
/// </summary>
/// <param name="migrationBusiness"></param>
public SyncUpJob (IServiceScopeFactory serviceScopeFactory)
{
this.serviceScopeFactory = serviceScopeFactory;
}
private IServiceScopeFactory serviceScopeFactory;
/// <summary>
///
/// </summary>
public void Execute()
{
// call the method to run weekly
using (var serviceScope = serviceScopeFactory.CreateScope())
{
IMigrationBusiness migrationBusiness = serviceScope.ServiceProvider.GetService<IMigrationBusiness>();
migrationBusiness.SyncWithMasterData();
}
}
}