我正在使用.net 6
我正在嘗試使用 CosmosDb,并且正在關注本教程。問題是它們僅基于設定的容器 ID 進行實體化appsettings.json
這就是 Program.cs 的方式
static async Task<CosmosDbService> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
{
var databaseName = configurationSection["DatabaseName"];
var containerName = configurationSection["ContainerName"];
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new CosmosClient(account, key);
var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
var cosmosDbService = new CosmosDbService(client, databaseName, containerName);
return cosmosDbService;
}
builder.Services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(builder.Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
這就是控制器的樣子:
namespace demoCosmoDB.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
private readonly ICosmosDbService _cosmosDbService;
public UserController(ICosmosDbService cosmosDbService)
{
_cosmosDbService = cosmosDbService ?? throw new ArgumentNullException(nameof(cosmosDbService));
}
[HttpGet]
[Route("{Id:int}")]
public async Task<IActionResult> GetUser(string Id)
{
return Ok(await _cosmosDbService.GetUser(Id));
}
}
}
DbService 只是一個關于實作什么的介面:
假設我有另一個控制器 ArticleController,如何使用容器 id 實體化,例如“Articles”?
我試過:
static async Task<CosmosClient> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
{
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new CosmosClient(account, key);
return client;
}
但我不知道如何修改其余部分:
builder.Services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(builder.Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
....
uj5u.com熱心網友回復:
請不要為每個 Container 創建客戶端實體。創建單個CosmosClient實體并使用它來訪問同一帳戶中的任何和所有容器。
例如:
static CosmosClient InitializeCosmosClientInstance(IConfigurationSection configurationSection)
{
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new CosmosClient(account, key);
return client;
}
builder.Services.AddSingleton<CosmosClient>(InitializeCosmosClientInstance(builder.Configuration.GetSection("CosmosDb")));
namespace demoCosmoDB.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
private readonly Container _cosmosContainer;
public UserController(CosmosClient cosmosClient)
{
if (cosmosClient == null) {
throw new ArgumentNullException(nameof(cosmosClient));
}
_cosmosContainer = cosmosClient.GetContainer("dbName", "containerName");
// you can have different containers for different controllers
}
[HttpGet]
[Route("{Id:int}")]
public async Task<IActionResult> GetUser(string Id)
{
// use the Container to perform your operations
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459683.html
