C
C#•10mo ago
Maskoe

Does Hangfire create a new instance of my aspnetcore api?

Based on the documentation and some tests I did, it doesnt, but I'd like to be sure. I dont trust the docs and myself too much in this case. https://docs.hangfire.io/en/latest/index.html
These method invocations are performed in a background thread and called background jobs.
So it doesnt create a a new instance of my webapi every time it executes a job right? What I played with was this
BackgroundJob.Enqueue(() => DoSomething(DateTime.Now));

public async Task DoSomething(DateTime enqueuedAt)
{
coolSingletonService.Value++;
await Task.Delay(5000);
Console.WriteLine(coolSingletonService.Value);
}
BackgroundJob.Enqueue(() => DoSomething(DateTime.Now));

public async Task DoSomething(DateTime enqueuedAt)
{
coolSingletonService.Value++;
await Task.Delay(5000);
Console.WriteLine(coolSingletonService.Value);
}
So this actually does put out 1 2 3 4 ... So it IS the same instance of my webapi, which I can tell by the singleton service. If it was a different instance, it would start at 0 every single time. Now you should never do this, BUT that means hangfire jobs actually do work with application state somewhat. Obviously you cant guarantee your app hasnt restarted and hangfire executes a job right after. Even in FireAndForget scenarios. 🤔
1 Reply
FusedQyou
FusedQyou•10mo ago
With webapi it's the api as a whole that you run, right? You're not referencing a class specifically? Hangfire does not know of a webapi and it's merely a scheduler, it has no reason to run a second one
Want results from more Discord servers?
Add your server