我有一个 ASP.NET Core 8.0 Web API 的默认模板。我添加了以下包:
<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" />
运行应用程序时出现以下错误:
未处理的异常。 System.InvalidOperationException:当前JobStorage实例尚未初始化。您必须在使用 Hangfire 客户端或服务器 API 之前设置它。对于 .NET Core 应用程序,请在配置服务时根据您的应用程序类型调用 Hangfire.NetCore 或 Hangfire.AspNetCore 包中的
扩展方法,并确保使用基于服务的 API 而不是静态 API,例如IServiceCollection.AddHangfire
而不是IBackgroundJobClient
和BackgroundJob
而不是IRecurringJobManager
。RecurringJob
我尝试了以下 Hangfire 配置:
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());
}
}