The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure

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 content originally appeared on DEV Community and was authored by Mikael Krief

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

  1. Install Hangfire via NuGet
   Install-Package Hangfire
   Install-Package Hangfire.SqlServer
  1. Configure Hangfire in Program.cs (for .NET Core)
   builder.Services.AddHangfire(config => 
       config.UseSqlServerStorage("your_connection_string"));
   builder.Services.AddHangfireServer();
   app.UseHangfireDashboard();
  1. 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! 🚀


This content originally appeared on DEV Community and was authored by Mikael Krief


Print Share Comment Cite Upload Translate Updates
APA

Mikael Krief | Sciencx (2025-03-16T08:53:22+00:00) The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure. Retrieved from https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/

MLA
" » The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure." Mikael Krief | Sciencx - Sunday March 16, 2025, https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/
HARVARD
Mikael Krief | Sciencx Sunday March 16, 2025 » The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure., viewed ,<https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/>
VANCOUVER
Mikael Krief | Sciencx - » The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/
CHICAGO
" » The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure." Mikael Krief | Sciencx - Accessed . https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/
IEEE
" » The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure." Mikael Krief | Sciencx [Online]. Available: https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/. [Accessed: ]
rf:citation
» The Hangfire Cookbook: A Practical Guide to Background Job Processing in .NET and Azure | Mikael Krief | Sciencx | https://www.scien.cx/2025/03/16/the-hangfire-cookbook-a-practical-guide-to-background-job-processing-in-net-and-azure/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.