.net core 中通过 PostConfigure 验证 Options 参数
Intro#
在 .net core 中配置项推荐用 Options 来实现,有一些参数可能必须是用由用户来配置,不能直接写成默认值的参数,这样就需要就 Options 中的参数做一些校验,否则程序内部可能就会出现一些意想不到的异常,今天介绍一个比较简单的,通过 PostConfigure 的方式来实现Options 参数的校验。
实现#
在 PostConfigure 的委托中对所需验证的参数进行检查,如果参数不合法就抛一个异常出来,
在依赖注入获取这个 Option 的时候如果不满足条件就会抛出一个异常,而通过异常的 stacktrace 就可以看出来是哪里的错误了
public static IServiceCollection AddAliyunService(this IServiceCollection serviceCollection, Action<AliyunServiceOption> configAction) { if (configAction != null) { serviceCollection.Configure(configAction); } serviceCollection.PostConfigure<AliyunServiceOption>(options => { if (string.IsNullOrWhiteSpace(options.AccessKeyId)) { throw new ArgumentNullException(nameof(options.AccessKeyId), $"{nameof(AliyunServiceOption)} {nameof(options.AccessKeyId)} can not be null or empty"); } if (string.IsNullOrWhiteSpace(options.AccessKeySecret)) { throw new ArgumentNullException(nameof(options.AccessKeySecret), $"{nameof(AliyunServiceOption)} {nameof(options.AccessKeySecret)} can not be null or empty"); } }); serviceCollection.TryAddSingleton<IAliyunService, AliyunService>(); return serviceCollection; }在 Reference 中给出了一些其他的实现方式,可以参考,在此不做详细介绍。
.net core 3.0 会微软会给出一个更好的验证方式,详见 Options Validation: support eager validation
Reference#
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。https://www.cnblogs.com/weihanli/p/options-validation-via-post-configure.html
