1

I wan't to add some configuration to hangfire. It's easy going the documented way but there is one option that depends on User setting so I wan't to do it like this:

IGlobalConfiguration hangfireConfiguration = GlobalConfiguration.Configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings();

 if (Configuration.GetValue<bool>("HangfireUseMemoryStorage"))
 {
    hangfireConfiguration.UseMemoryStorage();
 }
    else
 {
    hangfireConfiguration.UseStorage(new MySqlStorage(
        Configuration.GetConnectionString("DefaultConnection"),
        new MySqlStorageOptions
        {
            TablesPrefix = "Hangfire"
        })
    );
};

But how to add a service with this configuration? Trying

services.AddHangfire(hangfireConfiguration);

leads to

cannot convert from 'Hangfire.IGlobalConfiguration' to 'System.Action<Hangfire.IGlobalConfiguration>'

So how can I add my configuration?

1 Answer 1

2

If you want to define the hangfire configuration, you will need to add it like this,

Taken from Hangfire Docs

Hangfire 1.7 Release Docs

// Add Hangfire services.
    services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), 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();

You can add the if/else on which storage to use based on Configuration.GetValue<bool>("HangfireUseMemoryStorage")

Sign up to request clarification or add additional context in comments.

2 Comments

But in this case I would have to duplicate the other settings.
Hangfire Documentation ... I would suggest checking section 6.1.6 and 6.1.7. In ASP.NET Core environments global configuration class is hidden inside the AddHangfire method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.