How to I get my Entity Framework Core DbContext to access it's Connection String from Azure Key Vault

Hunter K 40 Reputation points
2023-12-13T19:43:22.2666667+00:00

Hello I am using the following code in my Program.cs file to successfully retrieve my connection string stored as a secret in Azure Key Vault (something I can see while debugging). The question I have, is how do I get this value securely to my classes that inherit DbContext?

Program.cs

var builder = WebApplication.CreateBuilder(args);

var keyVaultEndpoint = new Uri(Environment.GetEnvironmentVariable("VaultUri"));

builder.Configuration.AddAzureKeyVault(keyVaultEndpoint,

    new DefaultAzureCredential(new DefaultAzureCredentialOptions

    {

        ManagedIdentityClientId = builder.Configuration["AzureADManagedIdentityClientId"]

    }));

Working to replace the following in my Class "CustomerContext" that inherits DbContext. (Connection string removed, but currently included)

  public CustomerContext()
  {
      //
      DbPath = "Data Source...";
  }

  protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(DbPath);
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
779 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.