在调用使用 DI 注入的 dbcontext(瞬态范围)的方法时,我收到“无法访问已处置的对象”异常 - 很可能 dbcontext 在调用时已被处置。该方法被流畅的调度程序作为作业调用:
JobManager.AddJob(
() => ExecuteUpdateDbContext(),
(s) => s.ToRunNow().AndEvery(60).Minutes()
);
ExecuteUpdateDbContext 方法可以在任何情况下工作,除非由流畅的调度程序使用。我是否需要对 ExecuteUpdateDbContext 方法做一些特殊的事情才能使其与流畅的调度程序一起工作?
我在使用流畅的调度程序或其他同步函数时遇到了同样的问题。
为此我创建了一个ServiceScopeFactory
对象并将其注入注册表的构造函数中。
我在startup.cs的Configure()函数中初始化了我的作业管理器 -
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
IServiceScopeFactory serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
JobManager.Initialize(new SchedulerRegistry(serviceScopeFactory));
}
调度程序注册表 -
public SchedulerRegistry(IServiceScopeFactory serviceScopeFactory)
{
Schedule(() => new SyncUpJob(serviceScopeFactory)).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
}
同步作业-
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();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)