Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best DI registration Scope for CloudTableClient class on ASP.NET Core [closed]

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
    }
}
like image 716
shumach5 Avatar asked Mar 21 '19 03:03

shumach5


2 Answers

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.

like image 130
Dave Avatar answered Oct 24 '22 07:10

Dave


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

like image 43
Vova Bilyachat Avatar answered Oct 24 '22 05:10

Vova Bilyachat