Wednesday, September 23, 2020

Azure Files Storage Development

We've been using an App Service in Azure since first developing our site (ResearchStory). An App Service allows you to run your code in the cloud with out having to maintain a full server or virtual machine. You get local storage but it's not unlimited (there is different storage levels by tier see: Azure App Service Tiers). It's also not easy to manage remotely. You can use Kudu and extensions (like Azure Web Apps Disk Usage) to view the data in a web browser but it's still a bit disconnected.

So we've decided to add Azure Files for storage of logs and generated reports. There are some samples and basic documentation but not a lot of extended examples. In particular I tried to find an example of how others were using the code to develop locally as well as use it in production yet keep the data separated.

I had first considered two storage accounts with separate connection strings like we do for database development but that seemed overly complicated. In the end, I created two root subfolders (one 'dev' and one 'prod') inside the Azure file share. During startup the code sets the root folder based on the environment and adds a scoped reference to DI.


services.AddScoped(client => {
	var shareName = WebEnvironment.IsDevelopment() ? "dev" : "prod";
	var connectionString = Configuration.GetConnectionString("StorageConnection");
	return new ShareClient(connectionString, shareName);
});

Then any code that needs to interact with the storage system will get it injected already configured to the right subfolder.


public async Task OnGetAsync(int id, [FromServices] ShareClient shareClient) {
	...
	var dirClient = shareClient.GetDirectoryClient("reports");
	await dirClient.CreateIfNotExistsAsync();
	...
}