I'm using in memory based Hangfire(1.6.21) within an ASP.net core (2.2) application. In Startup.cs
I'm configuring a service as a singleton:
services.AddSingleton<IXXXService, XXXService>(); // In ConfigureServices(...)
And also initiating Hangfire with this lines:
app.UseHangfireServer(); // In Configure(...)
Here's the simplified code of XXXService
:
public class XXXService : IXXXService
{
public ExternalAPIService()
{
Console.WriteLine("xxx");
}
public void QueueRequest(Guid requestId)
{
BackgroundJob.Enqueue(() => this.AnalyzeRequest(requestId));
}
public async Task AnalyzeRequest(Guid requestId)
{
Console.WriteLine("Analyzing request...");
}
}
The problem is that although XXXService
is defined as a singleton - and it really is created only once through consecutive requests, it is recreated by hangfire when eventually calling AnalyzeRequest
. How can I route hangfire to use the singleton object managed by the ASP's default DI?
IBackgroundJobClient
instead??! Docs clearly state thatBackgroundJob
is a wrapper aroundIBackgroundJobClient
– ApogeotropismIBackgroundJobClient
is relevant here. – SorosisConsole.WriteLine("xxx")
) - the second time is after the job is enqueued. The attached code is pretty minimal and reproduces the scenario so I'm not sure what else could be causing this. – Sorosis