Created
May 12, 2020 11:30
-
-
Save finesse-fingers/c65b2009639d18e2bfb7569be6a8ddf1 to your computer and use it in GitHub Desktop.
Using ConfigurationBuilder to add KeyVault as a provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ServiceExtensions | |
{ | |
/// <summary> | |
/// Creates a custom configuration for easier development of Azure Functions. | |
/// When environment is not Development, it adds support for keyvault | |
/// </summary> | |
/// <param name="builder"></param> | |
/// <returns></returns> | |
public static IConfiguration GetCustomConfiguration(this IFunctionsHostBuilder builder) | |
{ | |
IConfiguration localConfiguration; | |
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") | |
{ | |
localConfiguration = new ConfigurationBuilder() | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) | |
.AddEnvironmentVariables() | |
.Build() as IConfiguration; | |
// we have to replace the rootConfig with the new one | |
builder.Services.AddSingleton(localConfiguration); | |
} | |
else | |
{ | |
var rootConfig = builder.Services.BuildServiceProvider().GetRequiredService<IConfiguration>(); | |
var keyVaultBaseUrl = rootConfig.GetValue<string>("KeyVaultBaseUrl"); | |
// add keyvault | |
localConfiguration = new ConfigurationBuilder() | |
.AddAzureKeyVault(keyVaultBaseUrl) | |
.AddEnvironmentVariables() | |
.Build() as IConfiguration; | |
// we have to replace the rootConfig with the new one that has keyVault | |
builder.Services.AddSingleton(localConfiguration); | |
} | |
return localConfiguration; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment