IOptions pattern in Azure Functions

Published by Adrien DECONINCK
Category : .Net / Azure / Azure Functions Azure Key Vault
07/10/2025

The IOptions pattern is a mecanism provided by .NET to cleanly inject configuration into your application services. It allows you to automatically bind strongly-typed C# classes to a section of the application’s configuration, such as JSON files or Azure App Settings.

This pattern comes in three main interfaces, each suited for a specific need:

  • IOptions<T>: Provides a singleton configuration object, loaded only once when the application starts. It is used for scheduled or static functions where settings do not change often.
    • Example: Configuring an external endpoint or a fixed threshold.
  • IOptionsMonitor<T>: Allows you to retrieve the current configuration, with support for dynamic refresh and the ability to listen for changes via OnChange. Its usefulness depends on the configuration source: updating an App Setting in Azure restarts the Function App (which defeats the purpose of the refresh), whereas a secret updated in Key Vault (loaded via AddAzureKeyVault) can be reflected without a restart.
    • Example: Adjusting a polling interval or a log level configured dynamically via Key Vault or Azure App Configuration.
  • IOptionsSnapshot<T>: Provides a new configuration instance for each HTTP request (scoped).
    • Example: Multitenant applications that load options based on the currently logged-in user.

 
 

Why use IOptions in Azure Functions?

 

Thanks to its support for dependency injection and the .NET configuration model, Azure Functions allows you to adopt proven practices for clean and modular configuration.

IOptions offers several advantages in this context:

  • Readability and Maintainability: Settings are encapsulated in typed classes.
  • Security: Secrets are not hard-coded and can be sourced from a Key Vault.
  • Testability: It is easy to inject a mock configuration during tests.
  • Flexibility: Configuration can be modified on the fly with IOptionsMonitor.

 
 

Implementation Example in Azure Functions

 

Step 1 – Create a configuration class

First, we create a C# class relative to our parameters structures.

public class MySettings
{
    public string ApiKey { get; set; }
    public int TimeoutInSeconds { get; set; }
}

 

Step 2 – Define the configuration in appsettings.json

Then, we’ll add the corresponding section in the appsettings.json file to define values.

{ 
    "MySettings": 
    { 
        "ApiKey": "xyz-123", 
        "TimeoutInSeconds": 30 
    } 
}

 

Step 3 – Bind this section in Program.cs

At the application start, we bind this configuration section to our MySettings class using dependency injection.

builder.Services.Configure<MySettings>(
    builder.Configuration.GetSection("MySettings")
);

 

Step 4 – Inject the configuration into the function

Finally, we inject IOptions<MySettings> directly in the function constructor to be able to access the values in a typed and secured way.

public class MyFunction
{
    private readonly MySettings _settings;
    public MyFunction(IOptions<MySettings> options)
    {
        _settings = options.Value;
    }
    [Function("MyFunction")]
    public void Run([TimerTrigger("0 */5 * * * *")] TimerInfo timer, FunctionContext context)
    {
        var logger = context.GetLogger("MyFunction");
        logger.LogInformation($"Using API Key: {_settings.ApiKey}, Timeout: {_settings.TimeoutInSeconds}s");
    }
}

 
 

Securing Settings with Azure Key Vault

 

⚠️ Warning: Using Key Vault requires the application to have permission to access it. Ensure that the necessary permissions are in place in your Azure environment; otherwise, the configuration will fail silently or cause access errors.

To avoid exposing secrets in files or code, Azure Key Vault can be integrated into Azure Functions in two ways.

 

Method 1 – Direct References in App Settings

This method involves explicitly referencing a Key Vault secret in your Function App’s App Settings.

 

Step 1 – Create a Key Vault and add a secret

For example, add a secret named MySettings–ApiKey.

 

Step 2 – Link the secret in Azure App Settings

In your Function App > Configuration > Add an application setting:

MySettings:ApiKey = @Microsoft.KeyVault(SecretUri=https://<your-vault>.vault.azure.net/secrets/MySettings--ApiKey)

 

Step 3 – Use as usual with IOptions

The system will automatically inject the value from Key Vault.

 

Method 2 – Global Loading via AddAzureKeyVault()

This approach involves loading the entire content of the Key Vault into the configuration.

 

Step 1 – Add the NuGet package

First, add the Azure.Extensions.AspNetCore.Configuration.Secrets NuGet package to your project with :

dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets

 
Step 2 – Load the Key Vault in Program.cs

Then, modify the Program.cs file to load the Key Vault configuration at start.

builder.Configuration.AddAzureKeyVault(
new Uri("https://<mon-vault>.vault.azure.net/"),
new DefaultAzureCredential());

 

Step 3 – Name the secrets like the config keys

For example, a secret named MySettings–ApiKey (using to replace : because Key Vault does not allow colons in secret names) will be automatically mapped to the MySettings:ApiKey key.

 

Step 4 – Use via IOptions<MySettings>

The behavior is identical but more automated. However, be mindful of readability, especially when many secrets are injected automatically.

 
 

Advanced Features

 

Automatic Validation with Data Annotations

In most cases, options validation can be achieved using standard .NET attributes ([Required], [Range], etc.). Simply add the decorators to the properties of the configuration class:

public class MySettings
{
[Required]
public string ApiKey { get; set; }

[Range(1, 300)]
public int TimeoutInSeconds { get; set; }
}

//program.cs
builder.Services.AddOptions<MySettings>()
.Bind(builder.Configuration.GetSection("MySettings"))
.ValidateDataAnnotations()
.ValidateOnStart();

 

And chain the call to .ValidateDataAnnotations() in Program.cs:

builder.Services.AddOptions<MySettings>() 
.Bind(builder.Configuration.GetSection("MySettings")) 
.ValidateDataAnnotations() 
.ValidateOnStart();

 

Managing Multiple Configurations (Named Options)

To handle different variations of the same configuration, you can register multiple names:

builder.Services.Configure<MySettings>("ServiceA", config.GetSection("ServiceA")); 
builder.Services.Configure<MySettings>("ServiceB", config.GetSection("ServiceB"));

Then access each one based on the context:

var a = monitor.Get("ServiceA"); 
var b = monitor.Get("ServiceB");

This simplifies multi-client, multi-environment, or multi-service management.

 
 

Conclusion

 

The IOptions pattern is a foundational tool for designing maintainable and secure Azure Functions. By facilitating the injection of typed configuration and integrating natively with Azure services like Key Vault and App Configuration, it enables reliable governance of the application environment.