如何在 ASP.NET Core 8 中配置 Hangfire?

问题描述 投票:0回答:1

我有一个 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 包中的

IServiceCollection.AddHangfire
扩展方法,并确保使用基于服务的 API 而不是静态 API,例如
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());
    }
}
asp.net-core-webapi hangfire asp.net-core-8
1个回答
0
投票

你错过了这一行。

app.UseHangfireDashboard();

这是我这边的截图。

enter image description here

添加此行后,它在我这边起作用了。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.