C# 动态生成HangFire连接字符串.NetCore

C# 动态生成HangFire连接字符串.NetCore,c#,linq,asp.net-core,hangfire,C#,Linq,Asp.net Core,Hangfire,我有一个使用HangFire进行后台作业的项目,我需要动态更改连接字符串,而无需每次向任何客户运行此作业时手动更改代码,因为我有许多客户和许多数据库 基于此解决方案,我在startup和DbContext中对正常连接执行了此操作,效果非常好 我想对HangFire连接做同样的事情,这就是我现在使用的代码 services.AddHangfire(configuration => configuration.UseStorage( new M

我有一个使用HangFire进行后台作业的项目,我需要动态更改连接字符串,而无需每次向任何客户运行此作业时手动更改代码,因为我有许多客户和许多数据库 基于此解决方案,我在startup和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();

//...
/…假设已加载IConfiguration配置
//...
string connectionString=Configuration.GetConnectionString(“Hangfire”);//配置.UseStorage(

新建MySqlStorage(connectionString,//然后不要硬编码连接字符串。将其存储在appsettings.json文件中,并在启动时加载。这样,您只需编辑设置文件。@JimG。非常好的文章,感谢您的帮助。我并不认为它会这么简单,谢谢