I have an asp.net core MVC site where I need to use hangfire, then I have a hangfire server.
I need to use the hangfire dashboard only on the server. But if I don't use the app.UseHangfireDashboard(), the following exception happens.
Code
var configuration = builder.Configuration;
var hangfireConnectionStrings = configuration.GetConnectionString("Hangfire");
builder.Services.AddHangfire(conf =>
{
conf.UseSqlServerStorage(hangfireConnectionStrings);
conf.UseHangfireMediatR();
});
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 understand that it happened because there is some configuration pending, but I couldn't find any way to use hangfire without calling UseHangfireDashboard
or AddHangfireServer
.
I resolved it by creating this extension, the most important line here is
var gc = app.ApplicationServices.GetService<IGlobalConfiguration>();
I understand that it initialize the service.
public static class HangfireExtensions
{
public static IApplicationBuilder UseHangfire(this IApplicationBuilder app)
{
ArgumentNullException.ThrowIfNull(app, nameof(app));
var gc = app.ApplicationServices.GetService<IGlobalConfiguration>();
ArgumentNullException.ThrowIfNull(gc, nameof(gc));
ArgumentNullException.ThrowIfNull(JobStorage.Current, nameof(JobStorage.Current));
return app;
}
}