I have the following local.settings.json file:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"SureMdmApiKey": "xxx",
"SureMdmApiUrl": "xxx",
"SureMdmUsername": "xxx",
"SureMdmPassword": "xxx"
},
"ConnectionStrings": {
"StorageConnectionString": "aaaa",
"DataContext": "aaaa"
}
}
then I have the following code in Startup.cs file:
[assembly: FunctionsStartup(typeof(FunctionAppSureMdmSync.Startup))]
namespace FunctionAppSureMdmSync
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var services = builder.Services;
services.AddTransient<ISureMdmService>(s => new SureMdmService(
url: System.Environment.GetEnvironmentVariable("SureMdmApiUrl"),
username: System.Environment.GetEnvironmentVariable("SureMdmUserName"),
password: System.Environment.GetEnvironmentVariable("SureMdmPassword"),
apiKey: System.Environment.GetEnvironmentVariable("SureMdmApiKey")
));
var connString = System.Environment.GetEnvironmentVariable("ConnectionStrings:DataContext");
services.AddDbContext<DataContext>(options => options
.UseSqlServer(connString, x => x.UseNetTopologySuite()));
services.AddTransient<ITabletGroupService, TabletGroupService>();
services.AddTransient<ITabletService, TabletService>();
}
}
}
and it works fine on local
But when I publish this function to Azure Portal and go to "Configuration" and add "DataContext" to "Connection Strings":

My code does not work:
var connString = System.Environment.GetEnvironmentVariable("ConnectionStrings:DataContext");
How to get connection string? I want that it works both, on local and Portal Azure?
I’ve found that to access IConfiguration in Startup, you need to build a temporary service provider, that you just throw away. There might be better ways more recently, but it still works fine:
var configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
Then, don’t use System.Environment.GetEnvironmentVariable(), but IConfiguration instead (same applies for all your configuration):
var connString = configuration.GetConnectionString("DataContext");
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