Hangfire 无法按预期与 ASP.NET Core 3.1 一起使用

Hangfire not working with ASP.NET Core 3.1 as expected

不确定我做错了什么。

我已经设置了 Hangfire。

startup.cs中我添加了

public void ConfigureServices(IServiceCollection services) 
{
    ....

    // Add Hangfire services.
    services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(_configuration.GetConnectionString(Constants.AppSettingNames.DefaultConnectionStringName), new SqlServerStorageOptions
        {
            CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
            SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            QueuePollInterval = TimeSpan.Zero,
            UseRecommendedIsolationLevel = true,
            DisableGlobalLocks = true
        }));

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

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient backgroundJobs) 
{
    app.UseHangfireDashboard();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapBlazorHub();
            endpoints.MapControllerRoute("default", "{controller}/{action=Index}/{id?}");
            endpoints.MapHangfireDashboard();
        });

}

然后我有一个从控制器调用的服务

public class PublisherService
{
    public Publisher(IBackgroundJobClient backgroundJobs)
    {
        _backgroundJobs = backgroundJobs;
    }

    public void Publish()
    {
        // This works
        _backgroundJobs.Enqueue(() => Console.WriteLine("Rocky"));

        // This doesn't work
        _backgroundJobs.Enqueue(() => TestPublish());

    }

    private static void TestPublish() 
    {
        Console.WriteLine("Yo Adrian");
    }
}

这段代码似乎没有执行我的自定义方法TestPublish()

在我的控制器中调用

publisherService.Publish(); 

这可以正常工作:

_backgroundJobs.Enqueue(() => Console.WriteLine("Rocky"))

但是下面没有??

_backgroundJobs.Enqueue(() => TestPublish());

有什么想法吗?

谢谢

明白了,自定义方法需要 public

所以

private static void TestPublish()

需要

public static void TestPublish()

Enqueue 方法使用表达式而不是委托,因此它不会在调用上下文中执行。它会在稍后的某个时候执行,因此需要 public 可以访问。

此外,我没有正确设置 Hangfire 日志记录,所以看不到错误消息。

希望这对其他人有用