c# - 启动或类中的选项验证
问题描述
在 C# (ASP.NET Core) 中,我经常使用选项模式:
public class FooConfig
{
[Required]
public string MyString { get; set; }
}
public class Foo
{
private readonly FooConfig _config;
public Foo(IOptions<FooConfig> options)
{
_config = options?.Value ?? throw new ArgumentNullException(nameof(options));
}
public void DoSomething()
{
// Use _config.MyString here, e.g.:
Console.WriteLine("MyString starts with: " + _config.MyString[0]);
}
}
当我使用配置值时,我可以假设属性已经过验证吗?例如,我可以假设它MyString
不是空的吗?或者添加这样的额外检查是否更好:
public void DoSomething()
{
if (string.IsNullOrEmpty(_config.MyString))
{
throw [...];
}
Console.WriteLine("MyString starts with: " + _config.MyString[0]);
}
通常,我在应用程序启动时绑定选项时添加验证。但是,Foo
该类对启动一无所知,因此在Foo
.
services.AddOptions<FooConfig>()
.Bind(Configuration.GetSection("Foo"))
.ValidateDataAnnotations();
解决方案
Foo
can make whatever assumptions you are comfortable with it making - it's your code. As Ermiya commented, "always be defensive," and Options classes can be defensively written in multiple ways, such as the aforementioned attribute validation or IValidateOptions
approach, the options class providing reasonable default values, providing a readily accessible IsValid
method or equivalent, or encouraging DI registration through a carefully managed extension method.
Either the options class is your own, in which case you can build as much of this into the class as you determine it requires and therefore skip checking things piecemeal downstream, or the options class is provided by an external source outside of your control. In that case, like any third-party code, you should trust nothing: if you are injecting someone else's options classes, then you should take control of validating it meets your code's expectations, either through checking important properties before consuming them or even re-implementing or extending the options class with some sort of wrapper so that you know you're getting exactly what you expect.
推荐阅读
- python - Python PCA sklearn
- python -
在句子生成器上输出? - php - 如何用php连接mysql数据库?
- c# - 在 WPF 中,如何在 LostFocus 上进行绑定但在 PropertyChanged 上进行验证?
- javascript - 为什么我的下拉菜单只显示了一半?
- android - 如何使用 Flutter 使 Android 中的状态栏变暗?
- c - 为什么从用户信息输入时我必须在使用 fgets 之前使用 getchar
- python - 将 Python 数组转换为列表中的字符串 [Pandas]
- django - 如何知道您是否将两个套接字连接到 django 通道中的同一组通道层
- javascript - 打字稿中的嵌套数组过滤器()函数-总是返回true?