Search code examples
c#linqasp.net-corehangfire

Make dynamically HangFire connection string .NetCore


I have a project using HangFire for a background job and I need to change the connection string dynamically without needing to change the code manually every time I want to run this job to any customer as I've many customers and many Databases as well I've done this to the normal connection in the startup and DbContext based on this solution and works like a charm Dynamically change connection string in Asp.Net Core

and I want to do the same with the HangFire connection, and this is the code I'm using now

            services.AddHangfire(configuration => configuration.UseStorage(
            new MySqlStorage("server=127.0.0.1;uid=root;database=0046696-k; Allow User Variables=True",
            new MySqlStorageOptions()
            {
                TransactionIsolationLevel = (System.Transactions.IsolationLevel?)IsolationLevel.ReadCommitted,
                QueuePollInterval = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary = true,
                DashboardJobListLimit = 50000,
                TransactionTimeout = TimeSpan.FromMinutes(1),
                TablesPrefix = "Hangfire"
            })));
        services.AddHangfireServer();

Solution

  • Do not hard code the connection string.

    Store it in the appsettings.json file

    For example

    {
      "ConnectionStrings": {
        "Hangfire": "server=127.0.0.1;uid=root;database=0046696-k; Allow User Variables=True"
      }
    
      /* other settings */
    }  
    

    and load it at startup.

    //...Assume IConfiguration Configuration is loaded
    
    //...
    
    string connectionString = Configuration.GetConnectionString("Hangfire"); //<-- NOTE
    
    services.AddHangfire(configuration => configuration.UseStorage(
        new MySqlStorage(connectionString, //<-- NOTE
        new MySqlStorageOptions() {
            TransactionIsolationLevel = (System.Transactions.IsolationLevel?)IsolationLevel.ReadCommitted,
            QueuePollInterval = TimeSpan.FromSeconds(15),
            JobExpirationCheckInterval = TimeSpan.FromHours(1),
            CountersAggregateInterval = TimeSpan.FromMinutes(5),
            PrepareSchemaIfNecessary = true,
            DashboardJobListLimit = 50000,
            TransactionTimeout = TimeSpan.FromMinutes(1),
            TablesPrefix = "Hangfire"
        })));
    
    services.AddHangfireServer();
    
    //...
    

    That way you only need to edit the settings file as desired.

    If the options need to change dynamically as well then add a section in the settings to hold the desired options and load them in Startup.