Creating Azure Functions using IOptions with dotnet-isolated process 6.0

I’m writing this post because I found it extremely difficult to find a working example of this online. So, here is the answer I was waiting for:

Azure Functions is a serverless compute service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. In order to make it easier to manage and retrieve configuration settings in Azure Functions, the IOptions<T> interface can be used to bind custom settings to an IOptions instance.

To use IOptions<T> with Azure Functions, you first need to configure the HostBuilder to inject the Options Service to the middleware pipeline. Here is a working config

 

 public class Program
    {
        public static void Main()
        {
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                .ConfigureServices(services =>
                {
                    services.AddOptions<Settings>()
                    .Configure<IConfiguration>((settings, configuration)
                    => configuration.GetSection(nameof(Settings)).Bind(settings));
                })
                .Build();

            host.Run();
        }
    }

 
Next, add the Nuget packge for IOptions configuration to your .csproj file:

 <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" />

Next, create a custom configuration class that represents your settings. This class should have properties for each of the settings you want to bind to.

For example, if you have a MyCustomSetting settings in your local.settings.json file:

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "Settings:MyCustomSetting": "Foobar"
    }
}

and this is your Custom Settings class:

    public class Settings
    {
        public string MyCustomSetting { get; set; }
    }

Next, you can use dependency injection to bind an IOptions<T> instance to your Azure Function. In your function’s class, add a constructor that takes an IOptions<T> instance as a parameter, where T is your custom configuration class.

    public class Function1
    {
        private readonly ILogger logger;
        private readonly IOptions<Settings> settings;

        public Function1(
            ILogger<Function1> logger,
            IOptions<Settings> settings)
        {
            this.logger = logger;
            this.settings = settings;
        }

You can then access your settings in your function’s code by using the Value property on the IOptions<T> instance.

 [Function(nameof(Function1))]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {
            logger.LogInformation("C# HTTP trigger function processed a request.");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString($"Got My Custom Settings {settings.Value.MyCustomSetting}");

            return response;
        }

In this example, the Run method will log the values of MySetting1 and MyCustomSetting from the local.settings.json file.

Using IOptions<T> with Azure Functions can make it easier to manage and retrieve configuration settings in your functions. By creating a custom configuration class and binding an IOptions<T> instance to your function, you can access your settings in a strongly-typed and consistent way.

Written with the help of #ChatGPT