简体   繁体   中英

ASP.Net-Core option validation

I have written an extension method to IServiceCollection which takes an option delegate. My problem here is that I have to validate the configured options first (eg filter out null values) since it's unsafe to proceed and instantiate a service that relies on these options.

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);
    }
}

How can I validate here that the options are correctly specified without calling the delegate configureOptions ? I don't want to rely on default values from ServiceOptions since I want to make some settings mandatory.

ASP.NET Core 2.2+

docs

There is a validation method on the OptionsBuilder . The validation will occur on the first use of the IOptions<T>.Value property. It will throw an OptionsValidationException if not valid. Eager validation is tracked here .

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;
            });
    }
}

Alternatively, .ValidateDataAnnotations() is available too so the data annotation attributes are respected.

ASP.NET Core 2.0+

From ASP.NET Core 2.0 onwards, PostConfigure is a good fit. This function takes a configuration delegate too but is executed last, so everything is already configured.

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.Configure(configureOptions);
        services.PostConfigure<ServiceOptions>(options => {
            // Take the fully configured options and run validation checks...
            if (options.Option1 == null) {
                throw new Exception("Option1 has to be specified");
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM