frosty
frosty

Reputation: 2852

How to get IConfiguration in Azure Timer function in .Net 5

I need to get the IConfiguration in .Net 5 isolated process Azure functions to ConfigureServices using DI. How can I do this?

    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices(s => { 
            // Get IConfiguration
            // Configure services based on config settings
        })
        .Build();

Upvotes: 2

Views: 1299

Answers (1)

Métoule
Métoule

Reputation: 14472

You can use the ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate) overload.

That way, you can access the HostBuilderContext that contains the IConfiguration (as well as the IHostEnvironment if needed).

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices((hostBuilderContext, s) =>
    { 
        // Get IConfiguration
        var configuration = hostBuilderContext.Configuration;

        // Configure services based on config settings
           
    })
    .Build();

You can also customize the configuration if needed, via the ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate) method:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureAppConfiguration((hostingContext, configBuilder) =>
    {
        configBuilder
            .AddJsonFile("custom-settings.json", optional: true, reloadOnChange: true)
            ;
    })
    .ConfigureServices((hostBuilderContext, s) =>
    { 
        // Get IConfiguration
        var configuration = hostBuilderContext.Configuration;

        // Configure services based on config settings
           
    })
    .Build();

Upvotes: 12

Related Questions