I am writing C# code that runs against an Azure cloud. My application is an ASP.NET Core web service that exposes methods but no UI.
Sometimes I want to run my code locally using Microsoft Azure Storage Emulator. When my code starts up, one of the first things that happens is this:
var container = new BlobContainerClient(_connectionString, s);
bool exists = await container.ExistsAsync(ct);
if (!exists)
await container.CreateAsync(cancellationToken: ct);
When running locally, I sometimes forget to start Azure Storage Emulator. When that happens, it takes my code like a minute to time out and tell me it can't reach the "cloud".
What I want to achieve is: Make the program give me good error messages quickly when running locally, but use more lenient timeout strategies when actually running in the cloud.
I can reduce the above timeout by doing something like this:
var blobClientOptions = new BlobClientOptions();
blobClientOptions.Retry.MaxRetries = 0;
var container = new BlobContainerClient(_connectionString, s, blobClientOptions);
... but when running against the real cloud I don't want that; I want it to retry. One option might be to set the retries to zero like above, but only when running locally.
I have a development-specific configuration file (appsettings.Development.json
). Is it possible to configure such timeout/retry settings in the config file?
Or is there some other best-practice way to accomplish the "fail quickly in development" behaviour that I seek?
Thanks in advance!
public class BlobStorageConfiguration
{
public string ConnectionString {get; set;}
public int MaxRetries {get; set;}
}
appsettings.Development.json
{
...
"BlobStorageConfiguration": {
"ConnectionString " : "<your_connection_string>",
"MaxRetries ":0
}
...
}
Startup.cs
in the ConfigureServices
method..
var blobConfig = new BlobStorageConfiguration ();
Configuration.Bind(nameof(BlobStorageConfiguration ), blobConfig);
services.AddSingleton(blobConfig );
..
appsettings.Development.json
if you are running it locally:some controller:
[Route("api/somthing")]
[ApiController]
public class SomethingController : ControllerBase
private readonly ILogger<SomethingController > logger;
public SomethingController (
ILogger<SomethingController > logger,
BlobStorageConfiguration blobConfig)
{
this.logger = logger;
// use your blobConfig (connectionstring and maxRetries)
}