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
In Azure Functions v3 you can use the appsettings.json
configuration pattern from ASP.NET-Core with the ConfigureAppConfiguration
call below (reference).
Additionally, change the way you add your options by using the code within the Configure
method below. You should not be passing IConfiguration
to IServiceProvider.Configure<>()
. This will allow you to use an injected IOptions
object.
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
[assembly: FunctionsStartup(typeof(Startup))]
namespace MyAzureFunction
{
public class Startup : FunctionsStartup
{
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var context = builder.GetContext();
builder.ConfigurationBuilder
.AddAppsettingsFile(context)
.AddAppsettingsFile(context, useEnvironment: true)
.AddEnvironmentVariables();
}
public override void Configure(IFunctionsHostBuilder builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var configuration = builder.GetContext().Configuration;
builder.Services.Configure(options =>
{
configuration.GetSection("MachineLearningConfig").bind(options);
});
}
}
public static class ConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddAppsettingsFile(
this IConfigurationBuilder configurationBuilder,
FunctionsHostBuilderContext context,
bool useEnvironment = false
)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var environmentSection = string.Empty;
if (useEnvironment)
{
environmentSection = $".{context.EnvironmentName}";
}
configurationBuilder.AddJsonFile(
path: Path.Combine(context.ApplicationRootPath, $"appsettings{environmentSection}.json"),
optional: true,
reloadOnChange: false);
return configurationBuilder;
}
}
}