❔ Exception while using .BindConfiguration instead of .Configure

Hello !

I need some help to understand why I get an
System.InvalidOperationException
while I am using Option Pattern (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-7.0) with dependency injection.

The exception :
System.InvalidOperationException: No constructor for type 'Microsoft.Extensions.Options.ConfigurationChangeTokenSource`1[CustomOptions]' can be instantiated using services from the service container and default values.


My tests are using a custom helper which iterate through a IServiceCollection to retrieve service from default IoC by using IServiceProvider.GetService( ServiceDescriptor.ServiceType).

At the beginning I was registering my options this way (which cause the exception spoken above) :

services.AddOptions<CustomOptions>()
  .BindConfiguration(CustomOptions.SectionName);


I changed the registration for this way (which work perfect) :
services.AddOptions<CustomOptions>()
  .Configure<IConfiguration>((options, configuration) =>
    {
      const string sectionName = CustomOptions.SectionName;
      var section = configuration.GetSection(sectionName);

      if (!section.Exists())
        throw new OptionsValidationException(sectionName, typeof(CustomOptions),
          new[] { $"Missing section {sectionName}." });

      section.Bind(options);
})


The difference on the code from .BindConfiguration and .Configure :

  • .BindConfiguration use this instruction:
    optionsBuilder.Services.AddSingleton<IOptionsChangeTokenSource<TOptions>, ConfigurationChangeTokenSource<TOptions>>();
-.Configure use this instructio :
Services.AddTransient<IConfigureOptions<TOptions>>(sp =>
  new ConfigureNamedOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions));


Can someone explain the difference and why the first one throw an exception please ?
Thank you
Discover how to use the options pattern to represent groups of related settings in ASP.NET Core apps.
Was this page helpful?