Search code examples
c#databaseazureconnectionazure-cosmosdb

CosmosDB System.ArgumentNullException: 'Value cannot be null. (Parameter 'authKeyOrResourceToken')'


Currently I am getting the following error while trying to connect to my CosmosDB:

System.ArgumentNullException: 'Value cannot be null. (Parameter 'authKeyOrResourceToken')'

If I debug then I can see that section variable is null so I don't know why it is null because I call the section by the configuration with the exact same name of my appsettings.json

The error occurs in the following line of code:

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

The InitializeCosmosClientInstanceAsync method looks like that: enter image description here

In my Visual Studio it looks like that: description

My appsettings.json looks like that: enter image description here

Additionally the error message contains another description:

This exception was originally thrown at this call stack: [External Code] Program.$.__InitializeCosmosClientInstanceAsync|0_0(Microsoft.Extensions.Configuration.IConfigurationSection) in Program.cs [External Code] Program.$(string[]) in Program.cs


Solution

  • IN .NET6 IT IS IMPORTANT TO CONSIDER THAT THERE YOU HAVE TO REFACTOR CODE FROM DOCUMENTATION (.NET5) ACCORDING TO THE .NET6 CODING GUIDLINE!

    I fixed it by refactor the value of the parameters. If I use an appsettings.json then I also have to call these variables in my program.cs.

    New program.cs:

    async Task<CosmosDbService> InitializeCosmosClientInstanceAsync(
            IConfigurationSection configurationSection) {
        var databaseName = configurationSection.GetSection("DatabaseName").Value;
        var containerName = configurationSection.GetSection("ContainerName").Value;
        var accountUri = configurationSection.GetSection("Account").Value;
        var primaryKey = configurationSection.GetSection("authKey").Value;
        var client = new CosmosClient(accountUri, primaryKey);
        var cosmosDbService = new CosmosDbService(client, databaseName, containerName);
        var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
        await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
        return cosmosDbService;
    }
    
    builder.Services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(
    builder.Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());