An open API service indexing awesome lists of open source software.

https://github.com/wilsonneto-dev/strongly_typed_configurations_validations_example_ioptions

Some examples on how to validate the strongly typed configuration (IOptions)
https://github.com/wilsonneto-dev/strongly_typed_configurations_validations_example_ioptions

dotnet ioptions validation

Last synced: 3 months ago
JSON representation

Some examples on how to validate the strongly typed configuration (IOptions)

Awesome Lists containing this project

README

        

# Validating Strongly Typed Configurations (IOptions)

.Net 6 brings us some cool ways to validate the options, lazy or eager...
So, here are some examples on how to validate it

```csharp
// we can validate with data annotations
// the below validation will happen when we try to access it, not at the startup
builder.Services.AddOptions()
.Bind(builder.Configuration.GetSection("Rabbit"))
.ValidateDataAnnotations();

// we can use a method for the validation, this validation will happen when we try to access it
builder.Services.AddOptions()
.Bind(builder.Configuration.GetSection("Carrier"))
.Validate(
x => (!string.IsNullOrWhiteSpace(x.ApiUrl)) || (!string.IsNullOrWhiteSpace(x.Username)) || (!string.IsNullOrWhiteSpace(x.Pass)),
"There are problems with your Carrier configurations, pls check it...");

// we also can validate using an OptionValidate class as below
// this validation will happen at the stratup time! (Avoiding surprises \o/)
builder.Services.AddOptions()
.Bind(builder.Configuration.GetSection("Database"))
.ValidateOnStart();

builder.Services.AddSingleton, DatabaseOptionsValidation>();
```

Program file:

https://github.com/wilsonneto-dev/Strongly_Typed_Configurations_Validations_Example_IOptions/blob/master/TypedConfigurationsValidation_IOptions_Example/Program.cs