Simple method to implement the options pattern with 1 line of code.
License
—
Deps
18
Install Size
—
Vulns
✓ 0
Published
Apr 6, 2025
$ dotnet add package tiaringhio.ValidateOrThrow
Implement the Options Pattern with a single line of code, including validation on start and via Data Annotations.
Install package tiaringhio.ValidateOrThrow from Nuget.
Here's how via command line:
Install-Package tiaringhio.ValidateOrThrow
This package targets .NET standard 2.1 and above.
The option class you want to be added and validated must inherit from the following interface:
public interface IValidatedOption
{
/// <summary>
/// Name of the section in the appsettings.json (or secrets) file.
/// </summary>
public string SectionName { get; }
}
Like so:
public class ExampleOption : IValidatedOption
{
public string SectionName => "Example";
}
Then you will be able to add you option as a singleton like so:
builder.Services.AddOptionsOrThrow<ExampleOption>();
Note that the extension will throw:
InvalidOperationException when a section does not exist.OptionsValidationException when a requirement defined via Data Annotations is not met.