繁体   English   中英

如何将 CosmosDB 添加到 .Net 6 WebAPI?

[英]How to add CosmosDB to .Net 6 WebAPI?

我想在 .Net 6 WebAPI 中使用 CosmosDB SQL-API。 是否还有一个 AddCosmos() 方法可用于在不同的服务中注入客户端,或者是否真的有必要使用接口来实现我自己的 cosmos-service 以将客户端注入我自己的服务类?

在 .Net 6.0 中,您应该像下面的示例代码一样在您的“Program.cs”文件中添加“CosmosClient”。

using Microsoft.Azure.Cosmos;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "WebApplication1", Version = "v1" });
}); 
builder.Services.AddHttpClient();
builder.Services.AddSingleton<CosmosClient>(serviceProvider =>
{
    IHttpClientFactory httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();

    CosmosClientOptions cosmosClientOptions = new CosmosClientOptions
    {
        HttpClientFactory = httpClientFactory.CreateClient,
        ConnectionMode = ConnectionMode.Gateway
    };

    return new CosmosClient("<cosmosdb_connectionstring>");
    // sample code
    //return new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", cosmosClientOptions);
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication1 v1"));
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

然后你可以将CosmosClient注入你的控制器。

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;
using Microsoft.WindowsAzure.Storage.Table;

namespace WebApplication1.Controllers;
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    public CosmosClient _client;
    private readonly ILogger<WeatherForecastController> _logger;

    public HomeController(ILogger<WeatherForecastController> logger, CosmosClient client)
    {
        _logger = logger;
        _client = client;
    }
    [HttpGet]
    public async Task<string> getvalue() {
        string dbname = "test";
        string containername = "container1";
        Database database = await _client.CreateDatabaseIfNotExistsAsync(dbname);
        Container container = database.GetContainer(containername);
        var query = container.GetItemQueryIterator<Test>("SELECT c.id FROM c");
        string ss = string.Empty;
        while (query.HasMoreResults)
        {
            FeedResponse<Test> result = await query.ReadNextAsync();
            foreach (var item in result) {
                ss += item.id;
            }
        }
        return ss;
    }
    public class Test : TableEntity { 
        public int id { get; set; }
    }
}

测试结果

在我的 cosmosdb 中的价值。

在此处输入图片说明

通过 api 获取价值

在此处输入图片说明

这就是我所做的。

程序.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

//Start adding Congiguration for cosmos db
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 Microsoft.Azure.Cosmos.CosmosClient(account, key);
    var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
    await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
    var cosmosDbService = new CosmosDbService(client, databaseName, containerName);
    return cosmosDbService;
}

var section = builder.Configuration.GetSection("CosmosDb");
builder.Services.AddSingleton<ICosmosDbService>(
    InitializeCosmosClientInstanceAsync(section).GetAwaiter().GetResult());

//end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM