Search code examples
c#asp.net-coreconnection-stringhangfire

Loading Hangfire configuration from appsettings.json in ASP.NET CORE web app


I'm trying to use Hangfire with SQL Server, reading the connection string from the appsettings.json file. It doesn't work. Only when I provide the connection string to the UseSqlServerStorage method, does it work.

Here's appsettings.json:

{
  "ConnectionStrings": {
    "HangfireDemo": "Data Source=VSQL64;Initial Catalog=HangfireDemo;Integrated Security=SSPI;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}  

And here the line that configures Hangfire in Startup.ConfigureServices:

services.AddHangfire(configuration => configuration.UseSqlServerStorage("Data Source=VSQL64;Initial Catalog=HangfireDemo;Integrated Security=SSPI;"));  

If I write "HangfireDemo" in the UseSqlServerStorage method, it doesn't work. Only the full connection string in this method works.
How can I provide just the connection string name?


Solution

  • you should be able to do it something like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    
    
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    
    }
    
    
    public IConfigurationRoot Configuration { get; }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHangfire(configuration => 
        configuration.UseSqlServerStorage(Configuration.GetConnectionString("HangfireDemo"))
        );  
    
    }