Cannot access a disposed object (LoggerFactory)

We are using .NET 6, Hangfire.AspNetCore 1.7.31 and Hangfire.InMemory 0.3.4. This is how we configure Hangfire in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
  // ...
  
  services.AddHangfire(configuration =>
  {
    configuration.UseInMemoryStorage();
  });

  services.AddHangfireServer(x =>
  {
    x.WorkerCount = 5;
  });
  
  // ...
}

We have a unit test which calls RecurringJob.RemoveIfExists("jobId") somewhere in its body. This test was working for a long time and failed randomly today. We re-ran the test multiple times but we were unable to reproduce the exception.

Error message:

System.ObjectDisposedException : Cannot access a disposed object.
Object name: 'LoggerFactory'.

Stacktrace:

at Microsoft.Extensions.Logging.LoggerFactory.CreateLogger(String categoryName)
at Hangfire.AspNetCore.AspNetCoreLogProvider.GetLogger(String name)
at Hangfire.Logging.LogProvider.GetLogger(String name)
at Hangfire.Logging.LogProvider.GetLogger(Type type)
at Hangfire.Client.CoreBackgroundJobFactory..ctor(IStateMachine stateMachine)
at Hangfire.Client.BackgroundJobFactory..ctor(IJobFilterProvider filterProvider)
at Hangfire.RecurringJobManager..ctor(JobStorage storage, IJobFilterProvider filterProvider, ITimeZoneResolver timeZoneResolver, Func`1 nowFactory)
at Hangfire.RecurringJobManager..ctor(JobStorage storage, IJobFilterProvider filterProvider, ITimeZoneResolver timeZoneResolver)
at Hangfire.RecurringJobManager..ctor(JobStorage storage, IJobFilterProvider filterProvider)
at Hangfire.RecurringJobManager..ctor(JobStorage storage)
at Hangfire.RecurringJobManager..ctor()
at Hangfire.RecurringJob.<>c.<.cctor>b__21_0()
at System.Lazy`1.PublicationOnlyViaFactory(LazyHelper initializer)
at System.Lazy`1.CreateValue()
at Hangfire.RecurringJob.RemoveIfExists(String recurringJobId)
at OurApplication.Service.BL.Identity.OurServiceBL.DeleteHangfireRecurringJobIfHangfireIsEnabled(String jobId)

Why did the exception occur? How can we prevent it from happening again?

1 Like

Having the same here.

Discussing it here: Cannot access a disposed object (LoggerFactory) · Issue #2147 · HangfireIO/Hangfire · GitHub