我在这里找到了一个有用的链接:http: //marcelegger.net/azure-functions-v2-keyvault-and-iconfiguration#more-45
这对我有帮助,这就是我的做法。首先,我为 IWebJobsBuilder 接口创建了一个扩展方法。
/// <summary>
/// Set up a connection to AzureAppConfiguration
/// </summary>
/// <param name="webHostBuilder"></param>
/// <param name="azureAppConfigurationConnectionString"></param>
/// <returns></returns>
public static IWebJobsBuilder AddAzureConfiguration(this IWebJobsBuilder webJobsBuilder)
{
//-- Get current configuration
var configBuilder = new ConfigurationBuilder();
var descriptor = webJobsBuilder.Services.FirstOrDefault(d => d.ServiceType == typeof(IConfiguration));
if (descriptor?.ImplementationInstance is IConfigurationRoot configuration)
configBuilder.AddConfiguration(configuration);
var config = configBuilder.Build();
//-- Add Azure Configuration
configBuilder.AddAzureAppConfiguration(options =>
{
var azureConnectionString = config[TRS.Shared.Constants.CONFIGURATION.KEY_AZURECONFIGURATION_CONNECTIONSTRING];
if (string.IsNullOrWhiteSpace(azureConnectionString)
|| !azureConnectionString.StartsWith("Endpoint=https://"))
throw new InvalidOperationException($"Missing/wrong configuration value for key '{TRS.Shared.Constants.CONFIGURATION.KEY_AZURECONFIGURATION_CONNECTIONSTRING}'.");
options.Connect(azureConnectionString);
});
//build the config again so it has the key vault provider
config = configBuilder.Build();
//replace the existing config with the new one
webJobsBuilder.Services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), config));
return webJobsBuilder;
}
从 appsetting.json 读取 azureConnectionString 的位置,应包含 Azure 应用配置的 url。
完成后,我们需要在 Azure Func 项目中创建一个“启动”类,如下所示。
public class Startup : IWebJobsStartup
{
//-- Constructor
public Startup() { }
//-- Methods
public void Configure(IWebJobsBuilder builder)
{
//-- Adds a reference to our Azure App Configuration so we can store our variables there instead of in the local settings file.
builder.AddAzureConfiguration();
ConfigureServices(builder.Services)
.BuildServiceProvider(true);
}
private IServiceCollection ConfigureServices(IServiceCollection services)
{
services.AddLogging();
return services;
}
}
在我的 func 类中,我现在可以从我的 Azure 应用程序配置中提取值,就像它们在我的 appsetting.json 文件中所写的一样。
[FunctionName("FUNCTION_NAME")]
public async Task Run([ServiceBusTrigger("%KEYNAME_FOR_TOPIC%", "%KEYNAME_FOR_SUBSCRIPTION%", Connection = "KEY_NAME_FOR_SERVICEBUS_ENDPOINT")]Microsoft.Azure.ServiceBus.Message mySbMsg
, ILogger log)
{
log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg.MessageId}");
}