2

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?

Los Morales
  • 2,061
  • 7
  • 26
  • 42

1 Answers1

3

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();
        }
    }
}
Gaurav Jalan
  • 467
  • 2
  • 14