Hangfire is one of the most powerful background job processing libraries in the .NET ecosystem. Whether you're working with ASP.NET Core, .NET Framework, or integrating with Azure Services, Hangfire simplifies job scheduling, execution, and monitoring.
This cookbook-style guide combines fundamental, advanced, and integration recipes for mastering Hangfire in real-world .NET applications. Each recipe provides a use case, step-by-step implementation, and best practices.
π Chapter 1: Getting Started with Hangfire
1.1 Installing and Configuring Hangfire
Use Case
You need to set up Hangfire to handle background jobs in your .NET application.
Implementation
- Install Hangfire via NuGet
Install-Package Hangfire
Install-Package Hangfire.SqlServer
-
Configure Hangfire in
Program.cs
(for .NET Core)
builder.Services.AddHangfire(config =>
config.UseSqlServerStorage("your_connection_string"));
builder.Services.AddHangfireServer();
app.UseHangfireDashboard();
- Enqueue a Test Job
BackgroundJob.Enqueue(() => Console.WriteLine("Hello from Hangfire!"));
Best Practices
β Use a persistent database like SQL Server or Redis instead of in-memory storage.
β Secure the Hangfire dashboard to prevent unauthorized access.
1.2 Job Types in Hangfire
Use Case
You want to execute different types of jobs such as one-time, delayed, recurring, or continuation jobs.
Implementation
β Fire-and-Forget Jobs
BackgroundJob.Enqueue(() => SendEmail("user@example.com"));
β Delayed Jobs
BackgroundJob.Schedule(() => GenerateReport(), TimeSpan.FromMinutes(30));
β Recurring Jobs
RecurringJob.AddOrUpdate("daily-report", () => GenerateDailyReport(), Cron.Daily);
β Continuation Jobs
var jobId = BackgroundJob.Enqueue(() => ProcessOrder());
BackgroundJob.ContinueWith(jobId, () => NotifyCustomer());
Best Practices
β Use queues for prioritizing job execution.
β Set timeouts and automatic retries to handle failures.
π Chapter 2: Advanced Hangfire Techniques
2.1 Handling Job Failures and Retries
Use Case
You need to handle job failures gracefully and implement custom retry mechanisms.
Implementation
β Customize Retries
[AutomaticRetry(Attempts = 3, OnAttemptsExceeded = AttemptsExceededAction.Fail)]
public void SendEmail()
{
throw new Exception("SMTP server down!");
}
β Log Failed Jobs
public class LogFailureFilter : JobFilterAttribute, IServerFilter
{
public void OnPerformed(PerformedContext context)
{
if (context.Exception != null)
{
Console.WriteLine($"Job {context.BackgroundJob.Id} failed: {context.Exception.Message}");
}
}
}
GlobalConfiguration.Configuration.UseFilter(new LogFailureFilter());
Best Practices
β Monitor failed jobs in the Hangfire Dashboard.
β Implement job continuation for failure handling.
2.2 Using Dependency Injection in Jobs
Use Case
You need to use services like Entity Framework, Email Services, or APIs in Hangfire jobs.
Implementation
β Resolve Services with IServiceScopeFactory
public class OrderProcessor
{
private readonly IServiceScopeFactory _scopeFactory;
public OrderProcessor(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void ProcessOrders()
{
using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var orders = dbContext.Orders.Where(o => o.Status == "Pending").ToList();
foreach (var order in orders)
order.Status = "Processed";
dbContext.SaveChanges();
}
}
β Enqueue Job
BackgroundJob.Enqueue<OrderProcessor>(job => job.ProcessOrders());
Best Practices
β Avoid directly injecting DbContext; always use scoped services.
β Implement transactional processing to avoid partial updates.
π Chapter 3: Using Hangfire in Azure
3.1 Storing Hangfire Jobs in Azure SQL
Use Case
You need to persist Hangfire jobs in Azure for scalability and reliability.
Implementation
β Configure Hangfire to Use Azure SQL
GlobalConfiguration.Configuration.UseSqlServerStorage("Azure_SQL_Connection_String");
Best Practices
β Use Azure SQL with Read Replicas to balance the load.
3.2 Processing Jobs with Azure Storage Queues
Use Case
You want to offload Hangfire jobs to Azure Storage Queues for better scalability.
Implementation
β Push Jobs to Azure Queue
var queueClient = new QueueClient("Azure_Storage_Connection_String", "job-queue");
queueClient.SendMessage("Start Processing Order");
β Process Queue Messages with Hangfire
BackgroundJob.Enqueue(() => ProcessQueueMessage());
Best Practices
β Use Azure Service Bus for complex job orchestration.
π Conclusion
This Hangfire Cookbook covered:
β
Job scheduling & execution
β
Advanced job processing techniques
β
Integrating Hangfire with SignalR & Azure
β
Security & performance best practices
Want to go further? Next article : Running Hangfire in Kubernetes (AKS) or Microservices! π
Top comments (0)