I have hosted Azure Function V3 on Azure Linux environment. I am trying to read the connection string from the configuration section. But I am not getting it. I tried to put the connection string on both, Application Settings as well as Connection Strings sections as shown below.

I am using dependency injection and my Startup class looks like below.
using BHD.Data.Data;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
[assembly: FunctionsStartup(typeof(BHD.AzureFunctions.Startup))]
namespace BHD.AzureFunctions
{
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var sqlConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
builder.Services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(sqlConnection));
}
}
}
I get NullPointerException on ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString even though the connection string exists in local.settings.json file as shown below.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true"
},
"ConnectionStrings": {
"DefaultConnection": "<My connection string>"
}
}
The way to get configuration in Azure Functions 2+ is IConfiguration, not ConfigurationManager.
You can inject IConfiguration into most places where you might inject anything else, but in Startup() you need to use something like this trick instead.
IConfiguration will automatically read from your function app settings when hosting in Azure, and your local.settings.json when run locally.
Edit (references):
The documentation for this is IMHO neither clear nor easy to find. There is also a lot of related discussion and confusion on GitHub.
The main source is DI in Azure Functions 2. Within it, most of what you need to know is almost easily missed:
The function host registers many services. The following services are safe to take as a dependency in your application:
[...]
Microsoft.Extensions.Configuration.IConfiguration[...]
It also, in Working with options and settings says:
Values defined in app settings are available in an IConfiguration instance
The host does this for you; you do not need to do anything, and as above, it automatically gets settings from the correct source depending on your hosting context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With