Search code examples
c#asp.net-corehangfire

Is there a way to setup queue listening for hangfire in the "ConfigureServices" method in an Asp.NetCore console application?


Using the host builder of Asp.NetCore, I'm trying to Change the listened queue of Hangfire using a method that i could use in the "ConfigureServices" method.

I was wondering if I could do that or if I was obligated to use :

using (new BackgroundJobServer(options)) { /* ... */ } from The documentation or if there was another way.

Here's my main method

static void Main(string[] args)
{
    HostBuilder hostBuilder = new HostBuilder();
    hostBuilder.ConfigureServices(ConfigureServices);
    hostBuilder.Build().Run();
}

and Here's what my ConfigureServices method looks like :

public static void ConfigureServices(IServiceCollection services)
{
    services.AddHangfire(config =>
    {
        config.UsePostgreSqlStorage();
    });

    services.AddHangfireServer();
}

I expected AddHangfireServer to have an overload accepting an BackgroundJobServerOptions but I didn't find one.

Is there a way i missed an overload or do you set the listened queue another way completely?


Solution

  • Edit: services.AddHangfireServer(); will have an overload accepting BackgroundJobServerOptions as of Hangfire 1.7.5 (As seen here)

    Response for people with lower version of hangfire than 1.7.5:

    I looked into the code of the AddHangfireServer method and they're doing :

    var options = provider.GetService<BackgroundJobServerOptions>() ?? new BackgroundJobServerOptions();

    So a way of passing the BackgroundJobServerOptions would be to register it to the IoC container before calling the AddHangfireServer method.

    Here's my final ConfigureServices method :

    public static void ConfigureServices(IServiceCollection services)
    {
    
        //this was added
        services.AddSingleton(new BackgroundJobServerOptions()
        {
            //you can change your options here
            Queues = new[] { "etl" }
        });
    
        services.AddHangfire(config =>
        {
            config.UsePostgreSqlStorage();
        });
    
        services.AddHangfireServer();
    }