'Unable to connect with CosmosDB

I'm trying to connect a minimal API from .NET 6.0 with CosmosDB and I'm getting this error

Unable to resolve service for type 'Microsoft.Azure.Cosmos.CosmosClient' while attempting to activate 'AzureCS_API.db.CosmosDbService'.

As I'm new to minimal API I don't have enough experience to work with so I need a little bit of help. I'm pretty sure that I do have something else wrong so... any help is welcome

This is my Program.cs

var client = new TextAnalyticsClient(new Uri(Secrets.apiEndpoint), new AzureKeyCredential(Secrets.secretEndpoint));

var builder = WebApplication.CreateBuilder(args);

// COSMOSDB CONFIGURATION
static async Task<CosmosDbService> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
{
    var account = configurationSection["Account"];
    var key = configurationSection["Key"];
    var databaseName = configurationSection["DatabaseName"];
    var containerName = configurationSection["ContainerName"];

    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.AddHttpClient();
var db = builder.Services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(section).GetAwaiter().GetResult());
builder.Services.AddTransient<ICosmosDbService, CosmosDbService>();

var app = builder.Build();
app.MapGet("/", async ([FromServices] CosmosDbService db) => {});

app.MapGet("/{id}", async ([FromServices] CosmosDbService db, int id) => {});

app.MapPost("/", async (Message message, [FromServices] CosmosDbService db) => {});

and so on. This is my appsettings.json

"CosmosDb": {
  "Account": "",
  "Key": ,
  "DatabaseName": "",
  "ContainerName": ""
}

I think it's important to point out that the ICosmosDbService and its implementation are just the CRUD functions.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source