9

We need to add configuration providers to the native IConfiguration that is supplied to the Azure Functions natively. Currently we are completely replacing it with our custom Iconfiguration using the following code:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        ...

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddAzureKeyVault(...)
            .AddJsonFile("local.settings.json", true, true)
            .AddEnvironmentVariables()
            .Build();

        builder.Services.AddSingleton<IConfiguration>(configuration);

        builder.Services.AddSingleton<IMyService, MyService>();
    }
}

Some context

MyService needs in its constructor values from the KeyVault provider and also other instances like Application Insights, etc. If we leave the default IConfiguration, it doesn't have the KeyVault values. If we create the MyService instance with a factory, we need to manually provide the App Insights instance, etc. Currently replacing the IConfiguration compiles and the function runs. But it breaks other default behavior like not taking the configurations from the host.json (we are trying to configure the queue trigger). Using the default IConfiguration correctly reads the settings from host.json.

user33276346
  • 1,501
  • 1
  • 19
  • 38
  • It's not at all clear what the question is here. – Tom Biddulph Jul 17 '20 at 19:42
  • @Tom Instead of replace, we need to modify the IConfiguration that comes as default. – user33276346 Jul 17 '20 at 19:47
  • https://learn.microsoft.com/en-us/azure/azure-app-configuration/quickstart-azure-functions-csharp#connect-to-an-app-configuration-store – Aluan Haddad Jul 17 '20 at 20:44
  • @user33276346 Have a look at this https://stackoverflow.com/a/60078802/5233410 – Nkosi Jul 18 '20 at 02:59
  • @Aluan $438 a year, isn't there a coding workaround? – user33276346 Jul 23 '20 at 17:57
  • @Nkosi I tried your solution, however as Anthony Brenelière mentions, it replaces something in the function runtime. The problem is that Anthony Brenelière solution doesn't adapt to our needs as we need to pass the original configuration plus our particular configuration (files, KeyVault, etc) without altering the Function normal behavior. For example, we need to modify the number of retries for a queue trigger by setting that in host.json. If we leave the default injected config it works. But if we apply your solution or ours, it ignores the retry settings and follows the default behavior. – user33276346 Jul 23 '20 at 18:46
  • @Nkosi the host.json configuration I'm talking about: "extensions": { "queues": { "maxDequeueCount": 3, "visibilityTimeout": "00:00:30" } } Taken from https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-output?tabs=csharp#hostjson-settings – user33276346 Jul 23 '20 at 18:47

3 Answers3

18

There's a couple of comments about using a .NET Core Azure functions:

  1. When running locally, local.settings.json is loaded for you by default by the framework.
  2. You should avoid reading config values from appsettings.json or other files specially when running on the Consumption plan. Functions docs
  3. In general, you should refrain from passing around the IConfiguration object. As @Dusty mentioned, the prefer method is to use the IOptions pattern.
  4. If you're trying to read values from Azure Key Vault, you don't need to add the AddAzureKeyVault() since you can and should configure this in the azure portal by using Azure Key Vault References. Key Vault Docs. By doing this, the azure function configuration mechanism doesn't know/care where it's running, if you run locally, it will load from local.settings.json, if it's deployed, then it will get the values from the Azure App Configuration and if you need Azure Key Vault integration it's all done via Azure Key Vault references.
  5. I think it's also key here that Azure functions configuration are not the same as a traditional .NET application that uses appsettings.json.
  6. It can become cumbersome to configure the azure functions app since you need to add settings one by one. We solved that by using Azure App Configuration. You can hook it up to Azure Key Vault too.
  7. Application Insights is added by Azure Functions automatically. Docs

That being said, you can still accomplish what you want even though it's not recommend by doing the following. Keep in mind that you can also add the key vault references in the following code by AddAzureKeyVault()

var configurationBuilder = new ConfigurationBuilder();
var descriptor = builder.Services.FirstOrDefault(d => d.ServiceType == typeof(IConfiguration));
if (descriptor?.ImplementationInstance is IConfiguration configRoot)
{
    configurationBuilder.AddConfiguration(configRoot);
}

// Conventions are different between Azure and Local Development and API
// https://github.com/Azure/Azure-Functions/issues/717
// Environment.CurrentDirectory doesn't cut it in the cloud.
// https://stackoverflow.com/questions/55616798/executioncontext-in-azure-function-iwebjobsstartup-implementation
var localRoot = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
var actualRoot = $"{Environment.GetEnvironmentVariable("HOME")}/site/wwwroot";
var basePath = localRoot ?? actualRoot;
var configuration = configurationBuilder
    .SetBasePath(basePath)
    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: false)
    .AddEnvironmentVariables()
    .Build();

builder.Services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), configuration));

Let me know if you need more input/clarifications on this and I'll update my answer accordingly.

Dharman
  • 30,962
  • 25
  • 85
  • 135
lopezbertoni
  • 3,551
  • 3
  • 37
  • 53
  • 2
    Excellent response. Well explained, provides all the options, links to documentation, and even gives a code example. Would like to hear from OP and confirm that this works. – Troy Witthoeft Jul 29 '20 at 18:01
  • @TroyWitthoeft Thanks! I can confirm this works fine. Been down the Azure Functions configuration rabbit hole a few weeks ago. :) – lopezbertoni Jul 29 '20 at 18:07
1

Option 1: Bring in the base configuration prior to other config providers

// ...

var baseConfig = builder.Services.BuildServiceProvider().GetService<IConfiguration>();

var configuration = new ConfigurationBuilder()
    .AddConfiguration(baseConfig)
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddAzureKeyVault(...)
    .AddJsonFile("local.settings.json", true, true)
    .AddEnvironmentVariables()
    .Build();

// ...

Option 2: Make your custom dependencies finer-grained and use IOptions<T>

Instead of replacing the injected instance of IConfiguration or using Option 1 above, make your downstream services dependent on an IOptions<T>. I think this is the better pattern, as you can break your config up into small segments based on your needs, and have your services take more targeted dependencies.

var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddAzureKeyVault(...)
            .AddJsonFile("local.settings.json", true, true)
            .AddEnvironmentVariables()
            .Build();

// don't re-bind IConfiguration
// builder.Services.AddSingleton<IConfiguration>(configuration);

// instead, bind sections specific to what services may need
builder.Services.Configure<MyDbConfig>(config.GetSection("DbConfig"));

In this scenario, MyDbConfig is just a POCO with properties to host your config. Your service class takes the dependency on IOptions<MyDbConfig>:

public class MyService : IMyService
{
    private MyDbConfig _dbConfig;
    public MyService(IOptions<MyDbConfig> myDbConfig)
    {
        _dbConfig = myDbConfig.Value;
    }
}

In JSON based configs, you would include "DbConfig" (or whatever argument[s] you supply to GetSection) as a top-level JSON object, with your config values as properties in that object:

{
    "DbConfig": { "SuperSecretValue": "abc123" }
}

In KeyVault, you use -- to indicate the nesting pattern, with a Secret Name like DbConfig--SuperSecretValue.

Dusty
  • 3,946
  • 2
  • 27
  • 41
1

A simpler solution would be to override the ConfigureAppConfiguration method in your FunctionStartup class (https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#customizing-configuration-sources).

The following example takes the one provided in the documentation a step further by adding user secrets.

public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
    FunctionsHostBuilderContext context = builder.GetContext();

    builder.ConfigurationBuilder
        .SetBasePath(context.ApplicationRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
        .AddJsonFile($"appsettings.{context.EnvironmentName}.json", optional: true, reloadOnChange: false)
        .AddUserSecrets(Assembly.GetExecutingAssembly(), true, true)
        .AddEnvironmentVariables();
}

By default, configuration files such as appsettings.json are not automatically copied to the Azure Function output folder. Be sure to review the documentation (https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#customizing-configuration-sources) for modifications to your .csproj file. Also note that due to the way the method appends the existing providers it is necessary to always end with .AddEnvironmentVariables().

A deeper discussion on configuration in an Azure Function can be found at Using ConfigurationBuilder in FunctionsStartup

Terence Golla
  • 1,018
  • 1
  • 13
  • 12