How to Implement Hangfire in ASP.NET Core


Introduction to Hangfire in ASP.NET Core

Hangfire is a popular background job processing library for .NET applications. It allows you to run long-running tasks asynchronously without blocking your web server. Integrating Hangfire with ASP.NET Core is straightforward and provides a robust dashboard for monitoring jobs.

Prerequisites

Before you begin, ensure you have the following installed:

  • .NET 6 SDK or later
  • SQL Server or PostgreSQL (for the storage backend)
  • A Visual Studio or VS Code development environment

Step 1: Create a New Project

Start by creating a fresh ASP.NET Core Web API project:

// Create a new project using the command line
dotnet new webapi -n HangfireDemo
cd HangfireDemo

Step 2: Add Hangfire NuGet Packages

Next, install the required packages for Hangfire and its SQL Server storage:

// Install Hangfire core and SQL Server storage
dotnet add package Hangfire
dotnet add package Hangfire.SqlServer

Step 3: Configure Hangfire Services

In your Program.cs file, register Hangfire services and configure the storage connection string:

using Hangfire;
using Hangfire.SqlServer;

var builder = WebApplication.CreateBuilder(args);

// Add Hangfire services with SQL Server storage
builder.Services.AddHangfire(config =>
{
    config.UseSqlServerStorage(
        builder.Configuration.GetConnectionString("HangfireConnection"));
}, new SqlServerStorageOptions
{
    QueuePollInterval = TimeSpan.FromSeconds(15),
    QueueAttribute = "Queue"  // Optional: specify a default queue
});

var app = builder.Build();

// Ensure the database tables are created
app.UseHangfireServer();

app.MapHangfireDashboard();

app.Run();

Step 3.1: Configure Connection String

Add your SQL Server connection string to appsettings.json:

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=(localdb)\\mssqllocaldb;Database=HangfireDemoDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Step 4: Create a Background Job

Define a service class that contains the method you want to execute in the background. Decorate the method with the [Queue] attribute to assign it to a specific queue:

using Hangfire;
using Microsoft.Extensions.Logging;

public class EmailService
{
    private readonly ILogger _logger;

    public EmailService(ILogger logger)
    {
        _logger = logger;
    }

    // This method will be queued for background execution
    [Queue("email-queue")]
    public void SendWelcomeEmail(string userEmail)
    {
        _logger.LogInformation("Sending welcome email to {Email}", userEmail);
        // Simulate sending an email
        Thread.Sleep(5000);
        _logger.LogInformation("Welcome email sent successfully.");
    }
}

Step 5: Enqueue a Job from a Controller

Finally, inject IBackgroundJobClient into your controller and enqueue the job:

using Hangfire;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class JobsController : ControllerBase
{
    private readonly IBackgroundJobClient _backgroundJobClient;

    public JobsController(IBackgroundJobClient backgroundJobClient)
    {
        _backgroundJobClient = backgroundJobClient;
    }

    [HttpPost("send-email")]
    public IActionResult SendEmail(string email)
    {
        // Enqueue the background job
        _backgroundJobClient.Enqueue(() => new EmailService().SendWelcomeEmail(email));
        return Ok("Job enqueued successfully.");
    }
}
1 Comments Report