哪个是 ASP.NET Core 上 CloudTableClient 类的最佳 DI 注册范围

shu*_*ch5 7 c# azure azure-storage azure-table-storage

我正在使用 ASP.NET Core 2.2 和 Azure 表存储创建 Web 应用程序。由于 MicrosoftCloudTableClient在 Azure Storage SDK 中为我们提供了类,因此我将使用带有依赖注入 (DI) 的类。然而,在标准DI方法中,有三种方法来决定登记范围如AddScopedAddTransient,和AddSingleton。我的问题是哪个注册范围最适合CloudTableClient课堂。我认为这AddSingleton是最好的,因为不会发生连接池饥饿,我会像附加的示例代码一样使用它。但是,如果使用AddSingleton在某些方面不好(即性能或可靠性),我想得到一些建议。

//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
    }
}
Run Code Online (Sandbox Code Playgroud)

Vol*_*hat 2

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