Skip to content

Instantly share code, notes, and snippets.

@andrewmatveychuk
Created June 7, 2024 09:01
Show Gist options
  • Save andrewmatveychuk/058213eac0d8ac301b8c29fde8404c19 to your computer and use it in GitHub Desktop.
Save andrewmatveychuk/058213eac0d8ac301b8c29fde8404c19 to your computer and use it in GitHub Desktop.
Using the AddAzureClients method to initialize Azure clients from an appsettings.json file
// Extracts from a sample .NET Worker Service project
// You can add your target Azure resources in the Program.cs file using the 'AddAzureClients' method and extension methods from corresponding Azure services client libraries
// ...
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddAzureClients(clientBuilder => clientBuilder.AddSecretClient(builder.Configuration.GetSection("KeyVault")));
// ...
// Then you can 'inject' your Azure client into the Worker object (the Worker.cs file) and use them in your task
// ...
public Worker(ILogger<Worker> logger, SecretClient secretClient)
{
_logger = logger;
_secretClient = secretClient;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
try
{
KeyVaultSecret secret = await _secretClient.GetSecretAsync("myTestSecret1");
Console.WriteLine($"Secret value is: {secret.Value}");
}
catch (AuthenticationFailedException e)
{
Console.WriteLine($"[ERROR] Authentication Failed. {e.Message}");
}
await Task.Delay(1000, stoppingToken);
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment