Users Pricing

forum

Home Forums How to use Dependency Injection inside Hangfire Recurring Jobs in ASP.NET Core? – MindStick

How to use Dependency Injection inside Hangfire Recurring Jobs in ASP.NET Core?

Hemant Patel 14 17 Sep 2026

I am scheduling a daily recurring job in my ASP.NET Core application using Hangfire. My background task needs to access an Entity Framework Core DbContext to update database records.

The Dilemma with Scoped Services

Since DbContext is registered as a scoped service, resolving it directly in a background job often leads to an ObjectDisposedException if the scope closes early.

Example Job Code

// Class defining the job logic
public class EmailReportJob
{
    private readonly IApplicationDbContext _context;

    // Injecting scoped db context
    public EmailReportJob(IApplicationDbContext context)
    {
        _context = context;
    }

    // Method triggered by Hangfire
    public async Task ExecuteAsync()
    {
        // Perform operations on database
        var pending = await _context.Reports.Where(r => !r.IsSent).ToListAsync();
        // Send email logic here
    }
}

How does Hangfire handle service scope resolution when executing jobs? Does Hangfire create a new service scope for every job automatically, or do I need to explicitly create a scope using IServiceScopeFactory to avoid memory leaks and scoped services lifetime issues?


0 Answers

Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md