Azure Function - The ConnectionString property has not been initialized

Viewed 4704

I developed a Azure Function in Visual Studio and it works when published in Azure (since a year ago).

Now I made a template from that Azure Function, in Visual Studio, and I changed some details, but it's mainly the same. When I test it locally, it works fine.

But when I publish it in Azure and try to test it, I get this error:

The ConnectionString property has not been initialized

I usually write the Connection String in the Application Settings (and it works well for the older Azure functions).

Here is how the function gets the value of the Connection String:

var repo = new GranularRepository(ConfigurationManager.AppSettings["BoConnectionString"]);

I also tried:

var repo = new AvgDeliveryTime_GranularRepository(Environment.GetEnvironmentVariable("BodbConnectionString"));
2 Answers

According to your description, I could not distinguish your function runtime.

For v1:

You could use both ConfigurationManager.AppSettings and System.Environment.GetEnvironmentVariable to get your connection string in Azure.

var a = ConfigurationManager.AppSettings["BoConnectionString"];
var b = System.Environment.GetEnvironmentVariable("BoConnectionString");

For v2:

You could use System.Environment.GetEnvironmentVariable and ConfigurationBuilder to get it. Add ExecutionContext parameter, which is used to locate function app directory.

var a= System.Environment.GetEnvironmentVariable("BoConnectionString");
/////////////
public static void Run(...,ExecutionContext context)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(context.FunctionAppDirectory)
        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables()
        .Build();

    // Get Connection strings
    var connParameter= "MySqlAzureConnection";
    string connectionString = config.GetConnectionString($"{connParameter}");
}

Both of v1 and v2 you set the connection string in application settings. enter image description here

For more details, you could refer to this issue.

I fixed it by creating a new Azure Function project.

So my conclusion is that making a template from another Azure Function and using that as the new project, in Visual Studio, is creating issues.

Related