Using Hangfire in .NET 8 for Background Jobs
3 min readAug 14, 2024
What is Hangfire?
Hangfire is a library that facilitates the execution of background jobs within .NET applications. It provides a reliable mechanism to run tasks asynchronously, ensuring they do not interfere with the main thread’s execution. With features such as automatic retries, configurable job persistence, and easy-to-use dashboards, Hangfire is a preferred choice for managing background jobs in .NET.
Getting Started with Hangfire in .NET 8
Step 1: Create a New .NET 8 Project
dotnet new webapi -n HangfireDemo
Step 2: Install Hangfire
dotnet add package Hangfire
dotnet add package Hangfire.AspNetCore
Step 3: Configure Hangfire
using Hangfire;
using Hangfire.MemoryStorage;
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddHangfire(config =>
{
config.UseMemoryStorage(); // In-memory storage for simplicity; replace with a persistent storage in production
});
builder.Services.AddHangfireServer();
var app = builder.Build();
...
app.UseHangfireDashboard();
app.Run();
In this configuration:
AddHangfire
adds…