I have an Azure Function with DDD Architecture. My project structure looks like this: 
local.settings.json file Looks like this:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnectionString": "Endpoint=sb://sb.servicebus.windows.net/;*****"
},
"ConnectionStrings": {
"DefaultConnection": "Server=tcp:*************"
}
}
And my appsettings.json looks like this:
{
"ConnectionStrings": {
"DefaultConnection": "*******"
}
}
And ApplicationDbContextFactory file looks like this :
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
return new ApplicationDbContext(optionsBuilder.Options);
}
}
You need the specify the connection string prefix (see documentation):
Environment.GetEnvironmentVariable("CUSTOMCONNSTR_DefaultConnection");
This prefix classification is:
CUSTOMCONNSTR_ => Custom provider
MYSQLCONNSTR_ => MySQL
SQLAZURECONNSTR_ => Azure SQL Database
SQLCONNSTR_ => SQL Server
Credit goes to the people in this post:
Get Connection String in Azure Function v3
This is an annoying issue. Here are my findings:
local.settings.json
add your connection strings to the Values section with appropriate prefixes then get them in your function app by simply calling
Environment.GetEnvironmentVariable("yourConnString")
Azure App (or Function, etc.) Configuration
Add the same values to the ConnectionStrings section but without the prefixes
local.settings.json
add your connection strings to the ConnectionStrings section with appropriate prefixes then get them in your function app by calling
Environment.GetEnvironmentVariable("ConnectionStrings:yourConnString")
Notice the ConnectionStrings prefix! This will work locally but not in Azure because of that extra ConnectionStrings prefix. Can be addressed with some preprocessor directives though.
Azure App (or Function, etc.) Configuration
Add the same values to the ConnectionStrings section but without the prefixes
See this answer on how to inject IConfiguration to read the conn strings like
configuration.GetConnectionString("yourConnString")
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