动态制作 HangFire 连接字符串 .Net Core

Make dynamically HangFire connection string .NetCore

我有一个使用 HangFire 进行后台作业的项目,我需要动态更改连接字符串,而无需每次都手动更改代码,因为我想 运行 将此作业发送给任何客户许多客户和许多数据库 我已经根据此解决方案对启动和 DbContext 中的正常连接进行了此操作,并且工作起来很有魅力

我想对 HangFire 连接做同样的事情,这是我现在使用的代码

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

不要对连接字符串进行硬编码。

保存在appsettings.json文件中

例如

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

  /* other settings */
}  

并在启动时加载。

//...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();

//...

这样你只需要根据需要编辑设置文件。

如果选项也需要动态更改,则在设置中添加一个部分来保存所需的选项并在启动中加载它们。