Add a background job
Move work off the request path with Hangfire — one-off or recurring.
One-off
Enqueue from a handler; the request returns immediately and the job runs on the job server with its own retries:
csharp
_jobs.Enqueue(() => InvoiceJob.GenerateAsync(orderId));Recurring
Annotate a static method with a cron expression and it's scheduled at startup automatically — no central registration:
csharp
public static class ProjectJobs
{
[RecurringJob("0 3 * * *")] // every day at 03:00
public static async Task ArchiveStaleAsync()
{
using var scope = JobServices.Provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// … do the work
}
}DI inside a job
A job is static, so resolve services through JobServices.Provider.CreateScope() rather than constructor injection.
Watch it
The Hangfire dashboard at /hangfire (dev) shows queued, processing, succeeded, and failed jobs, and lets you retry by hand.
See Background jobs.