Hangfire is an open-source library for background job processing in .NET applications. It lets you run tasks asynchronously—for example, sending emails, processing images, or performing any lengthy operation—without blocking the main request thread. By handling job persistence, retries, and scheduling, Hangfire keeps your application responsive while ensuring critical background tasks are executed reliably.

Hangfire supports several types of jobs.

Prerequisites

Before you begin, ensure you have,

Setting Up the Sample Project

1. Create a New Minimal API Project

Open your terminal.

dotnet new web -n HangfireSample

2. Add Hangfire NuGet Packages

Navigate to your project folder and run.

cd HangfireSample
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
dotnet add Microsoft.Data.SqlClient

3. Configure the Database

Update appsettings.json with your connection string. For example, using LocalDB.

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=Instance;Database=Your_DB;Integrated Security=True;TrustServerCertificate=true;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

Hangfire will automatically create the necessary tables.

Implementing Hangfire in .NET 8

Replace the contents of Program.cs with the following code.

using Hangfire;
using Hangfire.SqlServer;

var builder = WebApplication.CreateBuilder(args);

// Configure Hangfire to use SQL Server storage.
builder.Services.AddHangfire(config =>
{
    config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"));
});

// Start the Hangfire Server to process background jobs.
builder.Services.AddHangfireServer();

// (Optional) Add Swagger for API testing.
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

// Use Swagger UI in development mode.
// Expose the Hangfire Dashboard at /hangfire (be sure to secure this in production).
app.UseHangfireDashboard();

// Root endpoint to test basic connectivity.
app.MapGet("/", () => "Hello World from .NET 8 and Hangfire!");

// Endpoint to enqueue a fire-and-forget job.
app.MapGet("/enqueue", (IBackgroundJobClient backgroundJobs) =>
{
    backgroundJobs.Enqueue(() => Console.WriteLine("Hangfire Fire-and-Forget Job executed!"));
    return Results.Ok("Background job has been enqueued.");
});
// New endpoint to schedule a delayed job (executes after 1 minute).
app.MapGet("/schedule", (IBackgroundJobClient backgroundJobs) =>
{
    backgroundJobs.Schedule(
        () => Console.WriteLine("Delayed Hangfire Job executed after 1 minute!"),
        TimeSpan.FromMinutes(1)
    );
    return Results.Ok("Delayed job scheduled to run after 1 minute.");
});

// Run the application.
app.Run();

How does This Work?

Hangfire Configuration

Endpoints

Visual Overview

Architecture Diagram

+-----------------------------+
|           Client           |
|   (Browser, Postman, etc.) |
+--------------+-------------+
               |
           HTTP Request
               |
               v
+-----------------------------+
|       .NET 8 Minimal API    |
| Endpoints:                 |
|   "/"         -> Hello World|
|   "/enqueue"  -> Enqueue    |
|   "/schedule" -> Delay      |
+--------------+-------------+
               |
     Enqueue / Schedule Command
               |
               v
+-----------------------------+
|   Hangfire Storage (SQL DB) |
+--------------+-------------+
               |
     Hangfire Server Polls
               |
               v
+-----------------------------+
| Hangfire Background Job     |
|        Processor            |
+-----------------------------+

Step-by-Step Flow

Key Terms Explained

Running and Testing

Start the Application

dotnet run

Test the Endpoints

Output Samples

Output Samples

Conclusion

This guide demonstrated how to integrate Hangfire into a .NET 8 Minimal API project, covering both immediate (enqueue) and delayed (schedule) job processing. By offloading long-running tasks to background jobs, you can keep your application responsive and scalable.

Next, consider exploring recurring jobs, job continuations, or integrating custom error handling to enrich your background processing capabilities.

Happy coding!