I am using .NET Core 8, there is no Startup file in my Solution. All the configuration and startup code are written directly in the Program.cs file itself.
Install Azure.Identity and Azure.Security.KeyVault.Secrets latest NuGet packages.
In appsettings.json, set the Key Vault URI.
"KVUri": "https://KVName.vault.azure.net/"
- Create a new class file
serviceTest.cs.
public class serviceTest
{
public class Secrets
{
public string Sec1 { get; set; }
public string Sec2 { get; set; }
}
private readonly Secrets _config;
public serviceTest(Secrets config)
{
_config = config;
}
public void GetSecrets()
{
Console.WriteLine("Secret1: " + _config.Sec1);
Console.WriteLine("Secret2: " + _config.Sec2);
}
}
- Retrieve the secrets in
Program.cs file and store them in the custom configuration Object Secrets.
My Program.cs file:
builder.Services.AddControllersWithViews();
var KVURI = builder.Configuration["KVUri"];
var client = new SecretClient(new Uri(KVURI), new DefaultAzureCredential());
var val1 = client.GetSecret("SampleKey").Value.Value;
var val2 = client.GetSecret("TestKey").Value.Value;
var secretConfig = new serviceTest.Secrets
{
Sec1 = val1,
Sec2 = val2
};
- Register the
serviceTest class using AddSingleton.
builder.Services.AddSingleton(secretConfig).AddSingleton<serviceTest>();
- Now you can call the
serviceTest class to retrieve the secrets somewhere in the code (Controller in my case)
private readonly serviceTest _st;
public HomeController(ILogger<HomeController> logger, serviceTest myService)
{
_logger = logger;
_st = myService;
}
public IActionResult Index()
{
_st.GetSecrets();
return View();
}
Output:

configobject?