C# IOptions Pattern for Azure Functions in an Isolated Worker Process .NET 8

441 views Asked by At

Has there been a change to the way the IOptions pattern is utilized in a .NET 8 Azure Functions in an Isolated Worker Process? I'm using the following code, and the dependency-injected IOptions object is always null.

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "Example:ClientId": "coke",
    "Example:ClientSecret": "g5419c734249b7ed86"
  }
}

Program.cs

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices((hostContext, services) =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.AddOptions<Example>().Configure<IConfiguration>((settings, configuration) =>
        {
            configuration.GetSection("Example").Bind(settings);
        });
    })
    .Build();

Options Class

public class Example
{
    public string ClientId { get; set; } = string.Empty;

    public string ClientSecret { get; set; } = string.Empty;
}

DI Constructor

public class MyClass(
    ILogger<MyClass> logger,
    IOptions<Example> exampleOptions)
{}    
2

There are 2 answers

1
javacavaj On

The issue is related to the use of a primary constructor. When I refactored the primary constructor:

public class MyClass(ILogger<MyClass> logger, IOptions<Example> exampleOptions){}

To a traditional constructor:

private ILogger<MyClass> logger;
private Example example;

public Acrobits(ILogger<MyClass> logger,IOptions<Example> exampleOptions)
{
    this.logger = logger;
    this.example = exampleOptions.Value;
}

The DI issue was resolved; however, all of the documentation I've read regarding primary constructors indicates DI of IOptions is supported.

0
Not Relevant On
public class MyClass(ILogger<MyClass> logger, IOptions<Example> exampleOptions)
{
  private readonly Example example = exampleOptions.Value;
}

should work!