[英]ASP.Net-Core option validation
我已经为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);
}
}
如何在不调用委托configureOptions
情况下验证选项是否正确指定? 我不想依赖ServiceOptions
默认值,因为我想强制执行一些设置。
OptionsBuilder
上有一个验证方法。 验证将在第一次使用IOptions<T>.Value
属性时进行。 如果无效,它将抛出OptionsValidationException
。 在这里跟踪热切的验证。
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;
});
}
}
或者, .ValidateDataAnnotations()
也可用,因此尊重数据注释属性。
从 ASP.NET Core 2.0 开始, PostConfigure
非常适合。 这个函数也需要一个配置委托,但最后执行,所以一切都已经配置好了。
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");
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.