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.
The `:` 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
public class AzureSearchConfig
{
public string IndexerName { get; set; }
public string IndexName { get; set; }
}
Then I could use Options pattern DI in startup
builder.Services.AddOptions<AzureSearchConfig>()
.Configure<IConfiguration>((settings, configuration) =>
{
configuration.GetSection("AzureSearch").Bind(settings);
});
In the Azure function where I need the setting, use it in a function
using System;
using Microsoft.Extensions.Options;
public class HttpTrigger
{
private readonly AzureSearchConfig _azureSearchConfig;
public HttpTrigger(IOptions<AzureSearchConfig> options)
{
_azureSearchConfig = options.Value;
}
}
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:
- Q&A on github: https://github.com/MicrosoftDocs/azure-docs/issues/82275
- Local Settings on Microsoft Docs: https://docs.microsoft.com/en-us/azure/azure-functions/functions-develop-local#local-settings-file
- Working with options and settings: https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#working-with-options-and-settings
What has your approach been to reading settings from configuration for Azure Functions?