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?
Can you answer this question?
Write Answer0 Answers