在 .Net 5 的辅助服务中配置 Hangfire 仪表板?

Configure Hangfire dashboard in a worker service in .Net 5?

我正在使用 Hangfire 来安排我的工作人员服务中的作业,并且想使用 hangfire 仪表板。但是好像没有办法配置这个。所有文档都使用 Startup class 但我的工作人员服务中没有任何启动。此外,.Net 5 不支持 OWIN NuGet 包。这是我尝试过的方法,

            var hostBuilder = CreateHostBuilder(args)
                .Build();

            var services = hostBuilder.Services;
            var applicationBuilder = new ApplicationBuilder(services);

            applicationBuilder.UseRouting();

            applicationBuilder.UseHangfireDashboard("/hangfire");

            applicationBuilder.UseEndpoints(endpoints =>
            {
                endpoints.MapHangfireDashboard();
            });

            hostBuilder.Run();

而且我已经像这样配置了 hangfire,

                 services.AddHangfire(configuration => configuration
                    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                    .UseSimpleAssemblyNameTypeSerializer()
                    .UseRecommendedSerializerSettings()
                    .UseSqlServerStorage("connection string",
                    {
                        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                        QueuePollInterval = TimeSpan.Zero,
                        UseRecommendedIsolationLevel = true,
                        DisableGlobalLocks = true
                    }));

                // Add the processing server as IHostedService
                services.AddHangfireServer();

请注意,在当前的实现中,我可以通过 hangfire 安排和执行作业,我现在需要的只是配置 hangfire 仪表板。

使用以下 Program.cs 配置 Hangfire 仪表板和您的工作人员服务:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args)
            .Build()
            .Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.Configure(app =>
                {
                    app.UseRouting();

                    app.UseHangfireDashboard();
                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapHangfireDashboard();
                    });
                });
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHangfire(conf => conf.UseSqlServerStorage("connection string"));
                services.AddHangfireServer();

                // your worker service
                services.AddHostedService<Worker>();
            });
}

Hangfire 仪表板将在 http://localhost:5000/hangfire 上可用。