Implementing Background Job Processing in .NET Core with Hangfire: A Step-by-Step Guide

Rahat Akhter
3 min readMar 18, 2023

Introduction

In this article, I will share my experience with Hangfire and provide a step-by-step guide on how to implement it in your .NET Core application.Asynchronous processing is a key requirement in many modern applications. In .NET Core, we have several libraries that support asynchronous processing. One such library is Hangfire, which allows you to easily execute background jobs in a reliable and scalable way. In this article, we will learn how to implement Hangfire in a .NET Core application.

Getting Started with Hangfire

Before we get started, we need to install the Hangfire package in our .NET Core application. To do this, open the NuGet Package Manager Console and run the following command

Install-Package Hangfire

Configuring Hangfire

Once the package is installed, we need to configure Hangfire in our application. In the ConfigureServices method of the Startup class, add the following code

public void ConfigureServices(IServiceCollection services)

{

// Other configuration code…

services.AddHangfire(config =>

{

config.UseSqlServerStorage(Configuration.GetConnectionString(“HangfireConnection”));

});

// Other configuration code…

}

This code configures Hangfire to use SQL Server as its storage backend. If you want to use a different storage backend, such as Redis or PostgreSQL, you can replace the UseSqlServerStorage method with the appropriate method for your chosen backend.

Next, we need to add the Hangfire middleware to our application pipeline. In the Configure method of the Startup class, add the following code

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

// Other configuration code…

app.UseHangfireDashboard();

app.UseHangfireServer();

// Other configuration code…

}

This code adds the Hangfire dashboard and server middleware to our application pipeline.

Creating Background Jobs with Hangfire

Now that we have Hangfire configured in our application, we can create background jobs using the BackgroundJob class. For example, let’s say we want to send an email to bulk user when you performed a bulk transactions We can create a background job to handle this by adding the following code to our TransactionController

public async Task<IActionResult> MakeTransaction(List<TransactionRequestModel> model)

{

// After Performing your Transactions or Performing Your Task…

BackgroundJob.Enqueue(() => SendEmail(model));

// Other Transaction code…

}

public void SendEmail(List<UserEmailRequestModel> model)

{

// Code to send registration email…

}

This code uses the BackgroundJob.Enqueue method to enqueue a job that will call the SendEmail method with the specified email address.

Best Practices for Hangfire

When using Hangfire, there are a few best practices that you should follow to ensure reliable and scalable background job processing

Use the Right Storage Backend

Choose a storage backend that fits the needs of your application. SQL Server is a good choice for most applications, but if you need more scalability, consider using a distributed storage backend such as Redis or PostgreSQL.

Avoid Long-Running Jobs

Long-running jobs can tie up resources and cause performance issues. Instead, break up long-running jobs into smaller, more manageable pieces.

Use Queues for Priority Jobs

If you have jobs that need to be processed with a higher priority, use queues to separate them from other jobs. This will ensure that they are processed first.

Monitor Job Processing

Monitor job processing to ensure that jobs are being processed as expected. Use the Hangfire dashboard to view job status and statistics.

Retry Failed Jobs

Hangfire automatically retries failed jobs by default. However, you can configure the retry behavior by setting the `Automatic

Conclusion

In conclusion, Hangfire is a powerful library that allows you to easily execute background jobs in your .NET Core application. By following the best practices we’ve discussed in this article, you can ensure reliable and scalable job processing in your application. I hope this article has been helpful in getting you started with Hangfire. If you have any questions or comments, feel free to leave them below. Happy coding!

--

--

Rahat Akhter

Senior Software Engineer with 5 yrs experience. Expert in .NET, JS, AWS, Microservices, Identity Server, GRPC, RabbitMQ, Hangfire, and Agile.