gpt4 book ai didi

azure - 如何使用 Azure.Data.Tables TableClient 进行依赖注入(inject)多个表?

转载 作者:行者123 更新时间:2023-12-02 23:56:12 25 4
gpt4 key购买 nike

https://learn.microsoft.com/en-us/azure/cosmos-db/table/create-table-dotnet?tabs=azure-portal%2Cvisual-studio#5---configure-the-table-client-in-startupcs

public void ConfigureServices(IServiceCollection services)
{
...

var connectionString = Configuration.GetConnectionString("CosmosTableApi");
services.AddSingleton<TableClient>(new TableClient(connectionString, "WeatherData"));

services.AddSingleton<TablesService>();
}

我明白这是如何工作的,但让我们介绍第二个表OceanData。这将如何运作?

services.AddSingleton<TableClient>(new TableClient(connectionString, "OceanData"));        
services.AddSingleton<OceanDataService>();
public HomeController(ILogger<HomeController> logger, TablesService tablesService, OceanDataService oceanDataService)

问题是当我调用 oceanDataService.GetAllRows 时,它会尝试查询 WeatherData 表!

public OcenDataService(TableClient tableClient)
{
_tableClient = tableClient;
}

看起来我应该做类似的事情

services.AddSingleton(new TableServiceClient(connectionString));

但我认为这是不对的,因为我只能访问服务类中的表名称,而不能访问表数据...

我哪里出错了?

最佳答案

您可以注入(inject)多个表,如下所示。

启动.cs:

builder.Services.AddSingleton<ITableStorageService<{TableName}>>(provider =>
new TableStorageService<{TableName}>(provider.GetRequiredService<TableServiceClient>(), nameof({TableName})));

TableStorageService.cs:

public class TableStorageService<T> : 
ITableStorageService<T> where T : class, ITableEntity, new()

{
private readonly TableClient _tableClient;

public TableStorageService(TableServiceClient tableServiceClient, string tableName)
=> _tableClient = tableServiceClient.GetTableClient(tableName);

public ValueTask<List<T>> QueryAsync(Expression<Func<T, bool>> query)
=> _tableClient.QueryAsync(query).ToListAsync();

public IEnumerable<T> GetAllRows()
{
return _tableClient.Query<T>();
}
}

关于azure - 如何使用 Azure.Data.Tables TableClient 进行依赖注入(inject)多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71472311/

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