Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Created February 8, 2023 18:10
Show Gist options
  • Save xiaomi7732/a0af8fc802a4a7624768f09fa0dc0074 to your computer and use it in GitHub Desktop.
Save xiaomi7732/a0af8fc802a4a7624768f09fa0dc0074 to your computer and use it in GitHub Desktop.
Clearly bind options for library code
  • NuGet packages:

    <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.2" />
  • Code

    public static IServiceCollection AddYourExtensionMethodName(this IServiceCollection services, string optionSectionName = "OPIOptions")
    {
        services.AddOptions<OPIClientOptions>().Configure<IConfiguration>((opt, configuration) =>
        {
            configuration.GetSection(optionSectionName).Bind(opt);
        });
    ...
        return services;
    }
@xiaomi7732
Copy link
Author

Consider using BindConfiguration extension method.
Namespace: Microsoft.Extensions.DependencyInjection
Package: Microsoft.Extensions.Options.ConfigurationExtensions.

It looks like the code could then be simplified:

public static IServiceCollection AddYourExtensionMethodName(this IServiceCollection services, string optionSectionName = "OPIOptions")
{
    services.AddOptions<OPIClientOptions>().BindConfiguration(optionSectionName);
...
    return services;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment