Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

c# - How to modify IConfiguration natively injected in Azure Functions

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...