How to add an appsettings.json file to my Azure Function 3.0 configuration?

后端 未结 6 630
轻奢々
轻奢々 2021-01-18 02:52

The new Azure Function 3.0 SDK provides a way to implement a Startup class. It gives access to the collection of services that are available by dependency injection, where I

6条回答
  •  遥遥无期
    2021-01-18 03:52

    With this .NET Core 3.1 and Azure Function 3. Spent a hours days. Here is what I came up with.

    [assembly: FunctionsStartup(typeof(Ugly.AzureFunctions.Startup))]
    
    namespace Ugly.AzureFunctions
    {
        class Startup : FunctionsStartup
        {
            public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
            {
                try
                {
                    // On Azure, we need to get where the app is.
                    // If you use Directory.GetCurrentDirectory(), you will get something like D:\Program Files (x86)\SiteExtensions\Functions\3.0.14785\32bit
                    var basePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..");
                    var environmentName = builder.GetContext().EnvironmentName;
                    builder.ConfigurationBuilder
                        .SetBasePath(basePath)
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
                        .AddEnvironmentVariables();
                }
                catch (Exception ex)
                {
                    // Handle exceptions about this. Which __should__ never ever happen.
                    // The previous comment is sarcastic.
                    throw;
                }
            }
    
            public override void Configure(IFunctionsHostBuilder builder)
            {
                try
                {
                    // DO NOT add the configuration as Singleton.
                    // If you need the IConfiguration:
                    //var configuration = builder.GetContext().Configuration;
    
                    builder.Services
                        .AddOptions()
                        .Configure((settings, configuration) => {
                            configuration.GetSection("MachineLearningConfig").Bind(settings);
                    });
                }
                catch (Exception ex)
                {
                    // Handle or not handle? That's the question.
                    throw;
                }
            }
        }
    }
    

提交回复
热议问题