I have a default template of a WebApi application with Asp.Net Core 8. 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 am receiving the following error message 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());
}
}