Search code examples
asp.net-core-webapihangfireasp.net-core-8

How to configure Hangfire in ASP.NET Core 8?


I have a default template of an ASP.NET Core 8.0 Web API. I added the following packages:

<PackageReference Include="Hangfire.AspNetCore" Version="1.8.14" />
<PackageReference Include="Hangfire.Core" Version="1.8.14" />
<PackageReference Include="Hangfire.MemoryStorage" Version="1.8.1.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />

I get the following error when running the application:

Unhandled exception. System.InvalidOperationException: Current JobStorage instance has not been initialized yet. You must set it before using Hangfire Client or Server API. For .NET Core applications please call the IServiceCollection.AddHangfire extension method from Hangfire.NetCore or Hangfire.AspNetCore package depending on your application type when configuring the services and ensure service-based APIs are used instead of static ones, like IBackgroundJobClient instead of BackgroundJob and IRecurringJobManager instead of RecurringJob.

I tried the following Hangfire configuration:

using Hangfire;
using Hangfire.MemoryStorage;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddHangfire(configuration => configuration
                    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
                    .UseSimpleAssemblyNameTypeSerializer()
                    .UseRecommendedSerializerSettings()
                    .UseMemoryStorage());

builder.Services.AddHangfireServer();

var app = builder.Build();

// ...other default WebApi code here...

var backgroundJob = new BackgroundJobClient();
backgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());

app.Run();

----

public class MyBackgroundJob
{
    public void ProcessJob()
    {
        File.AppendAllText(path, DateTime.UtcNow.ToString());
    }
}

Solution

  • You are missing this line.

    app.UseHangfireDashboard();
    

    Here is the screenshot in my side.

    enter image description here

    After adding this line, it works in my side.

    ....
    app.MapControllers();
    
    app.UseHangfireDashboard();
    
    var backgroundJob = new BackgroundJobClient();
    backgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());
    
    app.Run();
    

    enter image description here