我正在使用 ASP.NET Core 2.2 和 Azure 表存储创建 Web 应用程序。由于 MicrosoftCloudTableClient在 Azure Storage SDK 中为我们提供了类,因此我将使用带有依赖注入 (DI) 的类。然而,在标准DI方法中,有三种方法来决定登记范围如AddScoped,AddTransient,和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;
} …Run Code Online (Sandbox Code Playgroud)