Created
June 7, 2024 09:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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