MarleneHE
MarleneHE

Reputation: 374

Configuration is null when I use Dependency Injection to read the app settings of my Azure Function

I wrote an Azure Function that connects to a CosmosDB database through a Gremlin Server instance. In order to create the Gremlin Server instance, I need a few credentials that I saved in local.settings.json to debug locally, and that I wanted to retrieve through dependency injection.

To do so, I have created a custom type called CosmosDBCredentials, I have added a Startup class to my function app, and I have added a constructor to my function.

Here is the code of my newly created Startup class :


namespace FunctionApp1
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddOptions<CosmosDBCredentials>()
                .Configure<IConfiguration>((settings, configuration) =>
                {
                    configuration.GetSection("CosmosDBCredentials").Bind(settings);
                });
        }
    }
}

And here is the code of my function constructor that receives the options as parameters :

    public class Function1
    {
        private readonly CosmosDBCredentials _cosmosDBsettings;

        public Function1(IOptions<CosmosDBCredentials> cosmosDBsettings)
        {
            this._cosmosDBsettings = cosmosDBsettings.Value;
        }

When I excecute my function locally, the Startup class throws the following exception when it tries to bind the settings :

System.NullReferenceException: 'Object reference not set to an instance of an object.'

configuration was null.

I am quite confused as to what might have caused this, since I have followed the Microsoft documentation on how work with options and settings to the letter.

Any clue as to why the Startup class can't seem to resolve the IConfiguration ?

I a quite new to Dependency Injection in .NET Core projects and more specifically Azure Functions, please don't hesitate to correct me if my understanding is wrong.

Upvotes: 3

Views: 2394

Answers (1)

MarleneHE
MarleneHE

Reputation: 374

Thanks to @Ian Kemp, I finally found where my issue came from : I was using a version of the EPPlus NuGet package that was forcing Microsoft.Extensions.Configuration to update to a 3.x.x version, which is not compatible with Azure Functions v2. I reinstalled all my dependencies, and this time I selected an older version of the EPPlus NuGet package, which is dependent on the version of Microsoft.Extensions.Configuration that I need, and that solved the issue.

Upvotes: 3

Related Questions