gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:30 25 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 2.2 和 Azure 表存储创建 Web 应用程序。由于微软为我们提供了CloudTableClient Azure 存储 SDK 中的类,我将使用该类进行依赖注入(inject) (DI)。然而,在标准DI方法中,有三种方法来决定注册范围,例如 AddScoped , AddTransient ,和AddSingleton 。我的问题是哪个注册范围最适合CloudTableClient类(class)。我以为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
}
}

最佳答案

根据 published performance tips ,使用单例是实现客户端的正确方式。

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.

关于c# - ASP.NET Core 上 CloudTableClient 类的最佳 DI 注册范围是哪个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55273401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com