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

时间:2019-03-21 03:35:18

标签: c# azure azure-storage azure-table-storage

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
    }
}

2 个答案:

答案 0 :(得分:1)

AddScoped ,则它将为每个请求或 AddTransient 创建新的客户端,每次请求时都会为您提供新实例。如果您执行静态操作,那么所有线程将仅服务一个实例,这可能是一个问题,因为实例不能保证线程安全。

答案 1 :(得分:0)

按照published performance tips,使用单例是实现客户端的正确方法。

  

每个DocumentClient和CosmosClient实例都是线程安全的,并在直接模式下运行时执行高效的连接管理和地址缓存。为了允许SDK客户端进行有效的连接管理和更好的性能,建议在应用程序的生命周期内为每个AppDomain使用一个实例。