Cannot access a disposed object exception when method invoked by fluent scheduler job

◇◆丶佛笑我妖孽 提交于 2019-12-25 09:08:04

问题


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()
);

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?


回答1:


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.

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 -

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();
        }
    }
}


来源:https://stackoverflow.com/questions/45926159/cannot-access-a-disposed-object-exception-when-method-invoked-by-fluent-schedule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!