.netazureazure-blob-storage

BlobServiceClient singleton?


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.


Solution

  • 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.