首页 > 解决方案 > 启动或类中的选项验证

问题描述

在 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();

标签: c#validation

解决方案


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.


推荐阅读