1

I'm trying to create a custom ConfigureOptions class implementing IConfigureNamedOptions in .NET 4.8.

Here is the implementation

public class ConfigureAppSettings : IConfigureNamedOptions<AppOptions>
{
    private readonly IConfiguration configuration;

    public ConfigureAppSettings()
    {
        configuration = new ConfigurationBuilder().BuildAdapterConfiguration("appsettings.json");
    }

    public void Configure(AppOptions options)
    {
        Configure(nameof(AppOptions), options);
    }

    public void Configure(string name, AppOptions options)
    {
        IOptions<AppOptions> configurationOptions = Options.Create(configuration.GetSection(nameof(AppOptions)).Get<AppOptions>());
        options = configurationOptions.Value;
    }
}

When configuring the dependency injection container the services.ConfigureOptions<ConfigureAppSettings>(); is called.

But then, when I want to use IOptionsSnapshot<AppOptions>, Value is null.

While debugging options is set inside the Configure method but when exists it, options reference is not preserved and is null.

How can I get the value set in Configure method?

Side note: I need this implementation because on Configure method I also need to call an HTTP service to the some options properties.

Eduard Stefanescu
  • 411
  • 2
  • 9
  • 19
  • How about showing your appsettings file? I reckon you don't have a section called "AppOptions" in the root of the json. – Neil Apr 12 '22 at 14:04
  • There is a section `AppOptions` because `Options.Create(configuration.GetSection(nameof(AppOptions)).Get());` returns the expected properties from `appsettings.json`. The problem is that `options` parameter from `Configure` method doesn't "persist" the changes. – Eduard Stefanescu Apr 12 '22 at 14:24
  • What you are trying to do here is _replacing_ the object reference to `AppOptions options`. This does not work since the `options` parameter is not a `ref` parameter. Therefore, you should also get a warning `IDE0059 Unneccessary assignment of a value to 'options'`. You get the warning because the assignment has no effect. I am looking at the same task: to replace the entire `options` object in Configure()` without manually replacing every single object property. Hopefully, there is someone who knows a better way. – DhyMik Jul 11 '22 at 13:51

0 Answers0