简体   繁体   中英

Hangfire activator not disposing

I am having trouble with Hangfire not disposing the objects it instances within a WebApi on NET 5.

This is my configuration in "ConfigureServices()" (pretty standard, btw):

services.AddScoped<ITestService, TestService>(); // I have also tried with "AddTransient()"

services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("Default")));
services.AddHangfireServer();

Then, I have the following line to configure a recurring job in "Configure()":

public void Configure(IApplicationBuilder app,
                      IWebHostEnvironment env,
                      IHttpContextAccessor httpContextAccessor,
                      ITestService testService)
{
    // Omitting other configure code here

    RecurringJob.AddOrUpdate("Check", () => testService.Test(), Cron.Minutely); // You can try "*/1 * * * ? *" to speed it up
}

As you can see "ITestService" is being injected through IoC.

FYI, "ITestService" is a "IDisposable". If I put breakpoints both in the constructor and in the "Dispose()" method, the constructor is called every interval, whereas "Dispose()" is never called.

This is an issue for me, since the service itself has other dependencies, like a Repository (ie: a SQL connection). Whenever the time passes, the app starts to break because it gets out of connections in the pool:

fail: Hangfire.Processing.BackgroundExecution[0] Execution Worker is in the Failed state now due to an exception, execution will be retried no more than in 00:05:00 System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

This error uses to be related to not disposing SQL connections, if I am not wrong.

So, do you think I am doing something incorrectly? Or could it be a bug?

EDIT:

If I put "this.Dispose()" at the end of TestService.Test(), and I manually dispose the Repository there, then the previous error is fixed. But I don't think that is a proper solution:S.

As said in the comments, you should use:

RecurringJob.AddOrUpdate<ITestService>("Check", t => t.Test(), Cron.Minutely);

Calling the method this way will trigger Dependency Injection for ITestServer and the instance will follow the expected life-cycle, with required call to Dispose()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM