To inject the KeyVault secret into the DatabaseSettings object
#1 You can write down the code as follow in program.cs file , configuration method
var keyVaultEndPoint = new Uri(builder.Configuration["VaultKey"]); var secretClient = new SecretClient(keyVaultEndPoint, new DefaultAzureCredential()); KeyVaultSecret kvs = secretClient.GetSecret(builder.Configuration["SecretName"]); string connectionString = kvs.Value; builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor() .AddMicrosoftIdentityConsentHandler(); builder.Services.Configure<DatabaseSettings>(options => { options.ConnectionString = connectionString; builder.Configuration.GetSection("Database").Bind(options); }); builder.Services.AddSingleton<TodoService>(); builder.Services.AddSingleton<RecipesService>(); builder.Services.AddSingleton<SpecialDatesService>();
#2. Modify the DatabaseSettings class in your appsettings.json file:
"Database": { "ConnectionString": "", "DatabaseName": "Personal", "TodoCollectionName": "todo", "RecipesCollectionName": "recipes", "SpecialDatesCollectionName": "specialdates" }
By binding the DatabaseSettings options, you can set the ConnectionString property using the retrieved value from the KeyVault secret while keeping the rest of the configuration intact.
Now, when you inject the DatabaseSettings object into your services, the ConnectionString property will be populated with the secret value from Azure Key Vault.
No comments:
Post a Comment