当流利的调度程序作业调用方法时,无法访问已处置的对象异常 [英] Cannot access a disposed object exception when method invoked by fluent scheduler job
问题描述
在调用使用注入了DI的dbcontext(瞬态作用域)的方法时,出现无法访问已处置的对象异常-很可能是在调用dbcontext时已经将其处置了。流利的调度程序正在将该方法作为作业调用:
I'm getting the "Cannot access a disposed object" exception during a call to a method that uses a DI-injected dbcontext (Transient-scoped)-- most likely the dbcontext was already disposed when being invoked. The method is being invoked as a job by fluent scheduler:
JobManager.AddJob(
() => ExecuteUpdateDbContext(),
(s) => s.ToRunNow().AndEvery(60).Minutes()
);
ExecuteUpdateDbContext方法在任何情况下都可以使用,除非由流利的调度程序使用。我需要对ExecuteUpdateDbContext方法做一些特殊的事情以使其与流畅的调度程序一起工作吗?
The ExecuteUpdateDbContext method works in any under circumstance except when used by fluent scheduler. Do I need to do something special with my ExecuteUpdateDbContext method to make it work with fluent scheduler?
推荐答案
我遇到了同样的问题流利的调度程序或其他同步功能。
为此,我创建了一个 ServiceScopeFactory
对象,并将其注入注册表的构造函数中。
I encountered the same problem with fluent scheduler or other synchronous functions.
For this I created a ServiceScopeFactory
object and injected it in the registry's constructor.
我初始化了startup.cs的Configure()函数中的作业管理器-
I initialized my job manager in Configure() function of startup.cs -
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
IServiceScopeFactory serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
JobManager.Initialize(new SchedulerRegistry(serviceScopeFactory));
}
SchedulerRegistry-
SchedulerRegistry -
public SchedulerRegistry(IServiceScopeFactory serviceScopeFactory)
{
Schedule(() => new SyncUpJob(serviceScopeFactory)).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
}
SyncupJob-
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();
}
}
}
这篇关于当流利的调度程序作业调用方法时,无法访问已处置的对象异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!