How to use complex settings in Azure Functions using Options pattern and Dependency injection

How to use complex settings in Azure Functions using Options pattern and Dependency injection

I only recently found out about this, so I had to share it immediately.

I have been using the Values section in the local.settings.json in a not-recommended way for some time.

Application settings in the local.settings.json has some naming restrictions which I have been ignoring as the way I used it seemed to work. The docs said:

Values must be strings and not JSON objects or arrays. Setting names can't include a colon (:) or a double underline (__).

This I thought was untrue, as I could declare setting names with : and it did work properly. So I raised a question and they responded and updated the docs - linked it to relevant details.

1The `:` in a Setting name is reserved for DI.

You could create complex settings with the same prefix and use the .NET Core DI, to read all related settings using the options pattern.

This is where, I think the GetSection("settingname") in combination with the Options pattern in full blown .NET Core Web Apps is slightly different from the one in Azure Functions.

Example

If I had several settings like AzureSearch:IndexName and AzureSearch:IndexerName in the Values section then creating a class by the name AzureSearchConfig and mapping the properties to the names of IndexName and IndexerName

1public class AzureSearchConfig
2{
3  public string IndexerName { get; set; }
4  public string IndexName { get; set; }
5}

Then I could use Options pattern DI in startup

1    builder.Services.AddOptions<AzureSearchConfig>()
2    .Configure<IConfiguration>((settings, configuration) =>
3    {
4        configuration.GetSection("AzureSearch").Bind(settings);
5    });

In the Azure function where I need the setting, use it in a function

 1using System;
 2using Microsoft.Extensions.Options;
 3
 4public class HttpTrigger
 5{
 6    private readonly AzureSearchConfig _azureSearchConfig;
 7
 8    public HttpTrigger(IOptions<AzureSearchConfig> options)
 9    {
10        _azureSearchConfig = options.Value;
11    }
12}

The GetSection call in Azure Functions, recognizes a section based on the setting name prefix. As long as the settings are grouped by the same prefix, the related options are read as one object.

References:

What has your approach been to reading settings from configuration for Azure Functions?

comments powered by Disqus