Search code examples
c#asp.net-corehangfire

Hangfire not working with ASP.NET Core 3.1 as expected


Not sure what I'm doing wrong here.

I've setup Hangfire.

In startup.cs I've added

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();
        });

}

Then I have a service that I call from a controller

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");
    }
}

This code doesn't seem to execute my custom method TestPublish().

In my controller I call

publisherService.Publish(); 

This works correctly:

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

but the following does not??

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

Any ideas why not?

Thanks


Solution

  • Figured it out, the custom method needed to be public

    so

    private static void TestPublish()
    

    needed to be

    public static void TestPublish()
    

    The Enqueue method uses an expression and not a delegate, so it doesn't get execute in the calling context. It get's executed at some point later so that needs to be publicly accessible.

    Also, I hadn't got Hangfire logging setup correctly so I couldn't see the error message.

    Hopefully this will be useful to somebody else