Reputation: 2834
I have a web api project where users can upload an image and I store in in an Azure blob. The code is as follows:
public class AzureImageHandler : IImageHandler
{
public async Task<string> StoreImage(byte[] image)
{
var storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
var blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
var container = blobClient.GetContainerReference("images");
// Create the container if it doesn't already exist.
container.CreateIfNotExists();
container.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
// Retrieve reference to a blob named "myblob".
var blockBlob = container.GetBlockBlobReference("myblob");
await blockBlob.UploadFromByteArrayAsync(image, 0, image.Length);
return blockBlob.Uri.ToString();
}
}
I have DI set up using Autofac and am wondering if any of the code is thread safe. i.e. Can I have a singleton container that all requests use to get a reference to a new blob or do I need to run this whole method each time? I couldn't find out if CloudStorageAccount/BlobClient/Container were thread safe.
Thanks
Upvotes: 2
Views: 3483
Reputation: 136136
From the documentation for CloudBlobContainer
class:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
I'm sure you will find similar thing for other classes as well.
If I may, I would like to make 2 suggestions:
container.CreateIfNotExists();
container.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
Following 2 lines of code gets executed for every request. If you're fairly certain that the blob container will be there in your storage account, you can remove these lines of code as both of these lines make network calls and could slow down your system. You could move this code in your application's startup if all of your users are uploading files in the same container.
Upvotes: 4