ASP.Net-Core选项验证

Bru*_*ell 5 c# dependency-injection .net-core asp.net-core

我编写了一个扩展方法,IServiceCollection其中包含一个选项委托.我的问题是我必须首先验证配置的选项(例如过滤掉null值),因为继续并实例化依赖于这些选项的服务是不安全的.

public static class ServiceCollectionExtensions {
    public static void AddServices(
        this IServiceCollection services,
        Action<ServiceOptions> configureOptions)
    {
        // Configure service
        services.AddSingleton<IAbstraction, Implementation>();

        // Validate options here...

        // Configure options
        services.Configure(configureOptions);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在此验证在不调用委托的情况下正确指定了选项configureOptions?我不想依赖默认值,ServiceOptions因为我想强制设置一些设置.

Bru*_*ell 8

从此以后OptionsBuilder,IOptions<T>.Value是一个很好的选择.此函数也采用配置委托,但最后执行,因此所有内容都已配置.

public static class ServiceCollectionExtensions {
    public static void AddServices(
        this IServiceCollection services,
        Action<ServiceOptions> configureOptions)
    {
        // Configure service
        services.AddSingleton<IAbstraction, Implementation>();

        // Configure and validate options
        services.AddOptions<ServiceOptions>()
            .Configure(configureOptions)
            .Validate(options => {
                // Take the fully configured options and return validity...
                return options.Option1 != null;
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 使用名称选项,您可以拥有多个例如"ServiceOptions"的实例,所有实例都具有不同的值.传递给`PostConfigureAll`的委托将为所有实例运行.更多信息[这里](http://www.jiodev.com/aspnet/core/fundamentals/Configuration/options#named-options-support-with-iconfigurenamedoptions) (2认同)