skip to Main Content

I am adding Blob Storage, while I am following this tutorial: https://www.learmoreseekmore.com/2022/11/dotnet7-webapi-azure-blob-storage-file-management-example.html

This piece:

builder.Services.AddScoped(_ =>
{
    return new BlobServiceClient(builder.Configuration.GetConnectionString("AzureStorage"));
});

if I use the connectingstring from the access Keys it is everytime blazing fast. responds in around 15ms. When I am falling back on the DefaultAzureCredentials the response is rather around the 40 seconds. Not very user-friendly 😉

If I follow this article from Microsoft: https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication/?toc=%2Fazure%2Fstorage%2Fblobs%2Ftoc.json&bc=%2Fazure%2Fstorage%2Fblobs%2Fbreadcrumb%2Ftoc.json&tabs=command-line

it states;

builder.Services.AddSingleton<BlobServiceClient>(x => 
    new BlobServiceClient(
        new Uri("https://<account-name>.blob.core.windows.net"),
        new DefaultAzureCredential()));

My question is about this singleton use; would this authentication managed by DefaultAzureCredential will give me errors some time? (BTW: respons back in 15ms!)
And is there not same overload as the use for AzureKeyVault:

it states:

builder.Configuration.AddAzureKeyVault(
new Uri(builder.Configuration["KeyVaultAddress"]),
new DefaultAzureCredential());

I am a bit surprised by the different notations from Microsoft.

2

Answers


  1. You can use singleton lifetime.
    The TokenCredential you give is used by Azure SDKs in their HTTP pipeline, so it will get a new access token when needed through that. It does not matter that the Storage service is singleton.

    Login or Signup to reply.
  2. DefaultAzureCredential acquires a token and caches it in the credentials instance. Token lifetime and refreshing is handled automatically, so you don’t need to worry about any of that.

    It is advisable to reuse Azure SDK clients throughout the application lifetime, so you should register them as singletons.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search