skip to Main Content

In the past developing a Timer Triggered Azure Function I’ve used GetConnectionStringOrSetting from Microsoft.Extensions.Configuration to load connection strings, secrets and regular settings. It didn’t matter where they lived, it would find them.

But in migrating to .NET 8 I’m not sure I should anymore? Looks like it depends on .NET standard and it no longer works with Microsoft.Extensions.Configuration.UserSecrets to load secrets from a secure folder when developing locally.

2

Answers


  1. Chosen as BEST ANSWER
    public static class IConfigurationExtensions
    {        
        /// <summary>
        /// Looks for a connection string by first checking the ConfigurationStrings section, and then the root.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="connectionName">The connection string key.</param>
        /// <returns></returns>
        public static string GetConnectionStringOrSetting(this IConfiguration configuration, string connectionName) =>
            configuration.GetConnectionString(connectionName) ?? configuration[connectionName];
    }
    

    I just ended up stealing that one static function so I wouldn't have to re-write all the calls to it.


  2. Is GetConnectionStringOrSetting deprecated?

    • In .NET 8, avoid using GetConnectionStringOrSetting and instead use the IConfiguration interface provided by Microsoft.Extensions.Configuration to access configuration settings to ensure compatibility with user secrets, environment variables, and configuration files.

    • I tried with the below code by using GetConnectionStringOrSetting not worked as expected.

    • To read from appsettings.json, environment variables, and user secrets. check below for sample configuration

    Program.cs:

    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    var host = new HostBuilder()
        .ConfigureFunctionsWebApplication()
        .ConfigureAppConfiguration((context, config) =>
        {
            var env = context.HostingEnvironment;
    
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                  .AddEnvironmentVariables();
    
            if (env.IsDevelopment())
            {
                config.AddUserSecrets<Program>();
                config.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
            }
        })
        .ConfigureServices(services =>
        {
            services.AddApplicationInsightsTelemetryWorkerService();
            services.ConfigureFunctionsApplicationInsights();
        })
        .Build();
    
    host.Run();
    

    To access the configuration setting in function use IConfiguration .

    Function1.cs:

    using System;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    namespace FunctionApp449034
    {
        public class Function1
        {
            private readonly ILogger _logger;
            private readonly IConfiguration _configuration;
    
            public Function1(ILoggerFactory loggerFactory, IConfiguration configuration)
            {
                _logger = loggerFactory.CreateLogger<Function1>();
                _configuration = configuration;
            }
    
            [Function("Function1")]
            public void Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer)
            {
                _logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    
                var connectionString = _configuration["MyDatabase"];
                var secretValue = _configuration["MySecret"];
    
                _logger.LogInformation($"Database Connection String: {connectionString}");
                _logger.LogInformation($"Secret Value: {secretValue}");
    
                if (myTimer.ScheduleStatus is not null)
                {
                    _logger.LogInformation($"Next timer schedule at: {myTimer.ScheduleStatus.Next}");
                }
            }
        }
    }
    
    

    local.settings.json:

    {
        "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "MyDatabase": "AccountEndpoint=https://pbazcdb.documents.azure.com:443/;AccountKey=sDhoF3BT060Ux5tpM4heCT7MSVT8BrDFmgFRTsBNRZbCpQIRS494sACDbM1GnUg==;",
        "MySecret": "simple"
      }
    }
    

    Output:

    enter image description here

    • For any further clarification required about packages and configurations refer this DOC.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search