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

后端 未结 6 625
轻奢々
轻奢々 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:36

    Nkosi's solution works pretty well, but it does update the way the azure function runtime loads settings for itself, by replacing IConfiguration singleton: services.AddSingleton.

    I prefer having another IConfigurationRoot that is not injected. I just need to inject my settings IOption that are linked to my own IConfigurationRoot.

    I build another IConfigurationRoot that is member of the Startup class:

    public class Startup : FunctionsStartup
    {
        private IConfigurationRoot _functionConfig = null;
    
        private IConfigurationRoot FunctionConfig( string appDir ) => 
            _functionConfig ??= new ConfigurationBuilder()
                .AddJsonFile(Path.Combine(appDir, "appsettings.json"), optional: true, reloadOnChange: true)
                .Build();
    
        public override void Configure(IFunctionsHostBuilder builder)
        {
             builder.Services.AddOptions()
                 .Configure>((mlSettings, exeContext) =>
                     FunctionConfig(exeContext.Value.AppDirectory).GetSection("MachineLearningSettings").Bind(mlSettings) );
        }
    }
    

    Note: connection strings must remain in the application settings, because it is required by triggers to create an instance of the the function app that is not started (in a consumption service plan).

提交回复
热议问题