How to access ConfigurationManager during host program startup?

40 views Asked by At

I'm setting up a Worker Service, and I need to pass a connection string to UseSqlServerStorage().

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<WorkerService>();
        services.AddHangfire(configuration => configuration
            .UseSqlServerStorage("NEEDS CONNECTION STRING HERE!"));
        services.AddHangfireServer();

    })
    .UseWindowsService()
    .Build();

In order to do that, I need to call ConfigurationManager.GetConnectionString(). But how can I access ConfigurationManager here?

1

There are 1 answers

0
Jonathan Wood On

The ConfigureServices method is overloaded and includes a method that takes a HostBuilderContext as the first parameter.

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        services.AddHostedService<WorkerService>();
        services.AddHangfire(configuration => configuration
            .UseSqlServerStorage(context.Configuration.GetConnectionString("HangfireConnection")));
        services.AddHangfireServer();
    })
    .UseWindowsService()
    .Build();