I am building a Web API using .NET Core 2.1. This will be hosted as an Azure Web App. I want to keep my database connection string in my Azure Key Vault. This is the code that I have put in my Startup.cs ConfigureServices method:
services.AddDbContext<dbContext>(async options =>
{
var keyVaultUri = new Uri("https://xxxxxxxxx.vault.azure.net/");
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
SecretBundle connectionStringSecret = await keyVaultClient.GetSecretAsync(keyVaultUri + "secrets/DBConnectionString");
options.UseSqlServer(connectionStringSecret.Value);
});
When I try to make an HTTP Get to my controller that has the dbContext injected into it I get the following error:
InvalidOperationException: No database provider has been configured
for this DbContext. A provider can be configured by overriding the
DbContext.OnConfiguring method or by using AddDbContext on the
application service provider. If AddDbContext is used, then also
ensure that your DbContext type accepts a DbContextOptions<TContext>
object in its constructor and passes it to the base constructor for
DbContext.
I am assuming that is is because of my use of the async lambda to get the connection string from the Key Vault, however, I'm not sure what to do about it. Is this the right way to get a connection string from Azure KeyVault for use in the Startup.cs? Should I do this a different way? Any help would be appreciated. Thanks.