I'm creating web application with ASP.NET Core 2.2 and Azure Table Storage. Since Microsoft provides us with CloudTableClient
class in Azure Storage SDK, I will use the class with Dependency Injection(DI). However, in standard DI approach, there are three methods to decide registration scope such as AddScoped
, AddTransient
, and AddSingleton
. My question is which registration scope is the best for CloudTableClient
class. I thought AddSingleton
is the best because connection pool starvation does not happen, and I will use it like attached sample code. But if using AddSingleton
is bad in some perspective(i.e. perf, or reliability), I would like to get some advice.
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//do something
services.AddSingleton(provider =>
{
var settings = Configuration["AzureStorageConnectionString"];
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(settings);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
return tableClient;
});
//do something
}
//SampleController
public class SampleController : Controller
{
private CloudTable _table { get; };
public SampleController(CloudTableClient tableClient)
{
_table = tableClient;
}
public async Task<IActionResult> GetSample(string id)
{
//do something with _table
}
}
Per the published performance tips, using a singleton is the correct way of implementing a client.
Each DocumentClient and CosmosClient instance is thread-safe and performs efficient connection management and address caching when operating in direct mode. To allow efficient connection management and better performance by the SDK client, it is recommended to use a single instance per AppDomain for the lifetime of the application.
AddScoped then it will create new client per request or AddTransient which will give you new instance each time you ask it. If you do static then only one instance will be served for all threads which could be an issue since instance dont give you guarantee that they are thread safe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With