这个要求来自测试的角度。我对 IOptions 模式很满意,因为它应该只加载配置中的内容,然后您可以使用验证来确保选项对象具有所需的内容。然而,当使用所述选项测试其他部分时,这会成为一个问题,因为您可以只用所需的很少的内容来更新该选项对象。
就我而言,我的选项对象如下:
public sealed record SomeOptions
{
public string Name { get; set; }
public string Description { get;, set; }
public Uri Location { get; set; }
}
我想确保每当在测试中创建 SomeOptions
时,名称和位置都必须反射(reflect)正常情况下验证所涵盖的内容。使用 SomeOptions
的无效实例进行测试似乎可能会回来咬我。
通常,我会通过构造函数鼓励这样做,但是当它尝试构建配置时,它会抛出 InvalidOperationException,因为它需要无参数构造函数。这里最好的方法是什么?目前,我已经将无参数构造函数与 XML 注释“请勿使用”结合在一起,但这似乎远远不够。
最佳答案
如果您可以迁移到 C# 11(很可能是 .NET 7),您可以使用新引入的 required
修饰符:
public sealed record SomeOptions
{
public required string Name { get; set; }
public string Description { get; set; }
public required Uri Location { get; set; }
}
如果不是,唯一的选择是编写自己的 custom analyzer .
关于c# - 使用 IOptions 模式时,如何使选项对象的属性成为强制属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76015821/