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.