问题
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