3

I have an Azure Function with DDD Architecture. My project structure looks like this: enter image description here

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);
        }
    }
Unknown Coder
  • 1,510
  • 2
  • 28
  • 56

2 Answers2

6

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

henda79
  • 465
  • 3
  • 13
2

This is an annoying issue. Here are my findings:

Option 1:

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

Option 2:

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

Option 3:

See this answer on how to inject IConfiguration to read the conn strings like

configuration.GetConnectionString("yourConnString")
ihor.eth
  • 2,207
  • 20
  • 27