Azure Functions: getting connection string from other file than local.settings.json

Viewed 985

I have a azure functions .net core 2.2 project. There is a class:

    public static class A
    {
        [FunctionName("abc")]
        public static async Task RunAsync(
            [ServiceBusTrigger("topic1", "sub1", Connection = "ServiceBusConnectionString")] string msg,
            [Inject] IInsertOrderAzureSqlFunction functionRunner)
        {
            //...
        }
    }

which uses ServiceBusTrigger. Connection for ServiceBusTrigger is obtained from local.settings.json file.
Is it possible to put connection string in different file i.e. secret.settings.json? How to enforce ServiceBusTrigger to get Connection parameter value from other file than local.settings.json

local.settings.json:

{
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
    "ServiceBusConnectionString": "connectionStringValue1",
    "SqlConnection": "connectionStringValue2"
  }
}
1 Answers

You can make use of the ConfigurationBuilder to add multiple secrets.settings.json or prod.settings.json etc and load it dynamically. Example code below.

Let's say you have a secrets.settings.json like this

{
  "ConnectionStrings": {
    "SqlConnectionString": "server=myddatabaseserver;user=tom;password=123;"
  },
  "MyCustomStringSetting": "Override Some Name",
  "MailSettings": {
    "PrivateKey": "xYasdf5678asjifSDFGhasn1234sDGFHg"
  }
}

Update 1

Make use of Dependency Injection using IWebJobsStartup and you can do it this way.

[assembly: WebJobsStartup(typeof(Startup))]
namespace MyFunctionApp
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {

            var config = new ConfigurationBuilder()
        .SetBasePath(context.FunctionAppDirectory)
        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
        .AddJsonFile("secret.settings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables()
        .Build();

        var myString = config["MyCustomStringSetting"];
         builder.Services.PostConfigure<ServiceBusAttribute(serviceBusOptions =>
            {
                serviceBusOptions.Connection = myString;
            });
        }
    }
}

The trigger will only fall back to using the options.ConnectionStringvalue if the connection string is not set by the attribute. So in your function definition, make sure to set ConnectionStringSetting to "":

Related