CommonNetFuncs.Hangfire 4.1.0

dotnet add package CommonNetFuncs.Hangfire --version 4.1.0
                    
NuGet\Install-Package CommonNetFuncs.Hangfire -Version 4.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CommonNetFuncs.Hangfire" Version="4.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CommonNetFuncs.Hangfire" Version="4.1.0" />
                    
Directory.Packages.props
<PackageReference Include="CommonNetFuncs.Hangfire" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CommonNetFuncs.Hangfire --version 4.1.0
                    
#r "nuget: CommonNetFuncs.Hangfire, 4.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CommonNetFuncs.Hangfire@4.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CommonNetFuncs.Hangfire&version=4.1.0
                    
Install as a Cake Addin
#tool nuget:?package=CommonNetFuncs.Hangfire&version=4.1.0
                    
Install as a Cake Tool

CommonNetFuncs.Hangfire

License NuGet Version nuget

This project contains helper methods and utilities for integrating Hangfire background job processing into ASP.NET Core applications with enhanced security, error handling, and graceful shutdown capabilities.

Contents


HangfireAuthorizationFilter

Authorization filter for Hangfire Dashboard that requires authenticated users with specific roles to access the dashboard.

HangfireAuthorizationFilter Usage Examples

<details> <summary><h4>Usage Examples</h4></summary>

Basic Setup with Roles

Restrict dashboard access to specific roles (Admin, Manager, etc.)

using CommonNetFuncs.Hangfire;
using Hangfire;
using System.Collections.Frozen;

// In Program.cs or Startup.cs
var allowedRoles = new HashSet<string> { "Admin", "Manager" }.ToFrozenSet();

app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization = new[] { new HangfireAuthorizationFilter(allowedRoles) }
});
Authentication Only (No Role Restrictions)

Allow any authenticated user to access the dashboard

using CommonNetFuncs.Hangfire;
using Hangfire;
using System.Collections.Frozen;

// Empty set = any authenticated user can access
var allowedRoles = new HashSet<string>().ToFrozenSet();

app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization = new[] { new HangfireAuthorizationFilter(allowedRoles) }
});

</details>


HangfireJobException

Custom exception for Hangfire background jobs that provides context about the job operation and controls retry behavior.

Properties:

  • OperationName - The name of the operation that failed
  • EntityId - The ID of the entity being processed when the failure occurred
  • AllowRetry - Whether Hangfire should retry the job (defaults to true)

HangfireJobException Usage Examples

<details> <summary><h4>Usage Examples</h4></summary>

Basic Job Exception

Throw a simple exception that allows retry

using CommonNetFuncs.Hangfire;

public async Task ProcessItem(int itemId)
{
    if (!await ValidateItem(itemId))
    {
        throw new HangfireJobException("Item validation failed");
    }
}
Exception with Retry Control

Throw an exception that prevents retry for permanent failures

using CommonNetFuncs.Hangfire;

public async Task ProcessPayment(int paymentId)
{
    var payment = await GetPayment(paymentId);

    if (payment.Status == PaymentStatus.AlreadyProcessed)
    {
        // Don't retry - this is a permanent failure condition
        throw new HangfireJobException(
            "Payment has already been processed",
            allowRetry: false);
    }
}
Exception with Operation Context

Provide operation name for better logging and debugging

using CommonNetFuncs.Hangfire;

public async Task SendEmailNotification(int userId)
{
    try
    {
        await emailService.SendNotificationAsync(userId);
    }
    catch (SmtpException ex)
    {
        throw new HangfireJobException(
            "Failed to send email notification",
            operationName: "SendEmailNotification",
            allowRetry: true);
    }
}
Full Context Exception

Include all context information for comprehensive error tracking

using CommonNetFuncs.Hangfire;

public async Task UpdateCustomerData(int customerId)
{
    try
    {
        var customer = await dbContext.Customers.FindAsync(customerId);

        if (customer == null)
        {
            throw new HangfireJobException(
                message: "Customer not found in database",
                operationName: "UpdateCustomerData",
                entityId: customerId,
                allowRetry: false); // Don't retry if customer doesn't exist
        }

        // Process customer...
    }
    catch (DbUpdateException ex)
    {
        throw new HangfireJobException(
            message: "Database update failed",
            operationName: "UpdateCustomerData",
            entityId: customerId,
            allowRetry: true); // Retry transient database errors
    }
}

</details>


HangfireShutdownMonitor

Monitors Hangfire jobs during application shutdown to ensure graceful termination and log pending jobs.

Features:

  • Logs pending job counts during shutdown (processing, enqueued, scheduled)
  • Properly disposes of the BackgroundJobServer
  • Handles errors gracefully during shutdown

HangfireShutdownMonitor Usage Examples

<details> <summary><h4>Usage Examples</h4></summary>

Register Shutdown Monitor

Add the shutdown monitor as a hosted service in your ASP.NET Core application

using CommonNetFuncs.Hangfire;

// In Program.cs or Startup.cs
builder.Services.AddHostedService<HangfireShutdownMonitor>();

// Configure Hangfire as normal
builder.Services.AddHangfire(configuration => configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage(connectionString));

builder.Services.AddHangfireServer();

The monitor will automatically log pending jobs when the application shuts down:

[INFO] Application shutting down with no pending Hangfire jobs

or

[WARN] Application shutting down with 5 pending Hangfire job(s): 2 processing, 2 enqueued, 1 scheduled.
       Jobs will be persisted in database and resumed by next instance.

</details>


WaitForHangfireJobsToComplete

Utility method to wait for all Hangfire jobs to complete before continuing execution. Useful for graceful shutdown scenarios or integration tests.

Parameters:

  • checkIntervalSeconds - How often to check job status (default: 5 seconds)
  • maxWaitMinutes - Maximum time to wait for jobs (default: 60 minutes)

WaitForHangfireJobsToComplete Usage Examples

<details> <summary><h4>Usage Examples</h4></summary>

Wait for Jobs with Defaults

Wait up to 60 minutes, checking every 5 seconds

using CommonNetFuncs.Hangfire;

public async Task ShutdownGracefully()
{
    logger.Info("Starting graceful shutdown...");

    // Wait for all Hangfire jobs to complete
    await WaitForHangfireJobsToComplete.WaitForAllHangfireJobsToComplete();

    logger.Info("All jobs completed, continuing shutdown");
}
Wait for Jobs with Custom Settings

Wait up to 10 minutes, checking every 10 seconds

using CommonNetFuncs.Hangfire;

public async Task RunIntegrationTest()
{
    // Enqueue test jobs
    BackgroundJob.Enqueue(() => ProcessTestData());
    BackgroundJob.Enqueue(() => ValidateResults());

    // Wait for jobs to complete before asserting results
    // Check every 10 seconds, timeout after 10 minutes
    await WaitForHangfireJobsToComplete.WaitForAllHangfireJobsToComplete(
        checkIntervalSeconds: 10,
        maxWaitMinutes: 10);

    // Assert test results...
}

The method logs progress while waiting:

[INFO] Waiting for 3 Hangfire job(s): 2 enqueued, 1 processing, 0 scheduled
[INFO] Waiting for 1 Hangfire job(s): 0 enqueued, 1 processing, 0 scheduled
[INFO] No pending Hangfire jobs found

If the timeout is exceeded:

[WARN] Maximum wait time of 10 minutes exceeded. Some jobs may still be pending.

</details>


Installation

Install via NuGet:

dotnet add package CommonNetFuncs.Hangfire

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on CommonNetFuncs.Hangfire:

Package Downloads
CommonNetFuncs.Email

Helper methods that deal with sending email, including an SMTP email sending service and an HTML email builder helper.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.1.0 40 6/5/2026
4.0.53 113 5/28/2026
4.0.43 116 5/14/2026
4.0.40 126 5/10/2026
4.0.39 117 5/10/2026
4.0.34 119 4/29/2026
4.0.31 138 4/21/2026
4.0.29 110 4/20/2026
4.0.23 118 3/30/2026
4.0.17 170 2/20/2026
4.0.13 149 2/4/2026
4.0.12 435 2/3/2026
3.8.42 140 3/5/2026
3.8.38 131 2/24/2026
3.8.33 150 2/2/2026