Why Background Jobs?
Imagine you're building an e-commerce platform. When a customer places an order, you don’t want to:
Send email confirmation
Update inventory
Generate invoice
Notify shipping partner
all in the same HTTP request.
Doing so would slow down the user experience or even cause request timeouts. This is where Hangfire steps in.
What is Hangfire?
Hangfire is a powerful open-source library that enables you to create, process, and manage background jobs in .NET — no Windows Service or separate process needed.
https://dotnetfullstackdev.medium.com/
✅ Easy to use
✅ Persistent (uses database)
✅ Supports retries, dashboards, and queues
✅ Works with ASP.NET, .NET Core, and others
Getting Started with Hangfire in ASP.NET Core
Step 1: Install NuGet Packages
Install-Package Hangfire
Install-Package Hangfire.AspNetCore
Install-Package Hangfire.SqlServer
Step 2: Configure Hangfire in Program.cs
builder.Services.AddHangfire(config =>
config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireDb")));
builder.Services.AddHangfireServer();
Step 3: Add Middleware in Program.cs
app.UseHangfireDashboard(); // Add before app.Run()
// Optional: Secure the dashboard
app.UseHangfireDashboard("/jobs", new DashboardOptions
{
Authorization = new[] { new MyAuthorizationFilter() }
});
Step 4: Create a Job
public class EmailService
{
public void SendWelcomeEmail(string userEmail)
{
// Simulate email sending
Console.WriteLine($"Email sent to {userEmail}");
}
}
Step 5: Fire Job from Controller
public class UsersController : Controller
{
private readonly EmailService _emailService;
public UsersController(EmailService emailService)
{
_emailService = emailService;
}
[HttpPost]
public IActionResult RegisterUser(string email)
{
// Fire-and-forget job
BackgroundJob.Enqueue(() => _emailService.SendWelcomeEmail(email));
return Ok("User registered successfully!");
}
}
Scheduled & Recurring Jobs
Delayed Job
BackgroundJob.Schedule(() => Console.WriteLine("Delayed job"), TimeSpan.FromMinutes(5));
Recurring Job
RecurringJob.AddOrUpdate(
"DailyReportJob",
() => Console.WriteLine("Sending daily report..."),
Cron.Daily);
Job Monitoring Dashboard
Hangfire comes with a built-in dashboard at /hangfire
or your configured route.
You can:
View succeeded, failed, and processing jobs
Retry failed jobs
Monitor queues
Security Tip
Restrict the dashboard in production:
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
return true; // Replace with your own logic
}
}
Best Practices
✅ Always use DI for services
✅ Offload time-consuming logic to jobs
✅ Use queues for job separation (emailQueue, billingQueue)
✅ Monitor dashboard regularly
✅ Handle exceptions and retries with care
Real-World Example: Order Processing System
Let’s say:
User places an order
API adds an order to DB
BackgroundJob triggers:
Inventory update
Email confirmation
Invoice PDF generation
Notification to shipping provider
Each of these can be separate jobs, even with dependencies (continuations).
Final Thoughts
Hangfire makes background processing in .NET elegant and reliable. Whether it's email delivery, data cleanup, reporting, or automation — Hangfire is a solid tool that fits right into your ASP.NET Core workflow.