C
C#13mo ago
kopuo

❔ Validation of appsettings configuration before running the application

Hello. I would like to validate entries in the appsettings configuration at application startup to check whether all required entries are set. I'm trying to do this with services.ValidateOnStart():
builder.Services
.AddOptions<ServiceBusSettings>()
.Bind(builder.Configuration.GetSection("Infrastructure:ServiceBus"))
.Validate(options =>
{
var properties = typeof(ServiceBusSettings).GetProperties();
foreach (var property in properties)
{
if (property.GetValue(options) == null)
return false;
}
return true;
}, $"None of the {typeof(ServiceBusSettings).Name} properties can be empty")
.ValidateOnStart();
builder.Services
.AddOptions<ServiceBusSettings>()
.Bind(builder.Configuration.GetSection("Infrastructure:ServiceBus"))
.Validate(options =>
{
var properties = typeof(ServiceBusSettings).GetProperties();
foreach (var property in properties)
{
if (property.GetValue(options) == null)
return false;
}
return true;
}, $"None of the {typeof(ServiceBusSettings).Name} properties can be empty")
.ValidateOnStart();
The problem here is that when building the application I use, among others: setting the AzureServiceBus host
...
cfg.Host(serviceBusConnectionString) //here it throws ArgumentNullException
...
cfg.Host(serviceBusConnectionString) //here it throws ArgumentNullException
I would like validation to be performed first, and if ServiceBusConnectionString is not set, return the appropriate validation message and not exceptions in other configuration places. Do you know any methods for such initial validation?
4 Replies
fasadin
fasadin13mo ago
on startup / program (depending which .net version you use) You should have Configure method where you do Use methods. There you can load your configuration and check all fields that you want and do action depending which you want if you want generic solution, you can make an attribute and then for your class that it's DTO for config, you can add that attribute
Joschi
Joschi13mo ago
There is also the validation source generator. But that may only be in .Net8 https://learn.microsoft.com/en-us/dotnet/core/extensions/options-validation-generator
Compile-time options validation source generation - .NET
Learn how to utilize compile-time source generation for validating options.
Omnissiah
Omnissiah13mo ago
i have this problem too and i'm thinkink of simply making an hosted service where i inject all the configurations instead of the ValidateOnStart crap
Accord
Accord13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server