DEV Community

Ahmed Shah
Ahmed Shah

Posted on

A Guide to Validations in the IOptions Pattern for .NET Developers

In the previous post I have talked about using named and typed IOptions pattern in .NET. link.

Let's see our C# class and appsettings file the we have created in previous article.

Image

Image description

Considering the complexities that can arise within large projects relying on multiple configurations, it's not uncommon for developers to overlook updating appsettings files, encountering null parameters, incorrect data types, or typographical errors in names. It happens, but it can lead to issues.

Now, imagine your pull request merged and the project cloned by another developer or deployed to production. Runtime surprises and missing settings become evident, sometimes without any exceptions.

To address this, we can employ validation techniques both at compile time and runtime within the IOptions pattern. Let's introduce data annotations into our C# class.

Image

Let change our Postal Code in Individual Company to string.

Image description

Notice I have individual Postal Code with a string value

now change the Company Settings in Startup to validate the data annotations.

first we will use compile time validations using .ValidateOnStart(); method on our Company settings like this in our program.cs file.

Image

Let Run our project and see what happens.

Image
As you see it throws exception for Company:Individual:PostalCode format exception which binds to string value instead of integer.

Now lets validate our appsettings during runtime and remove .ValidateOnStart().

Image

I have just modified controller for both Individual and Cooperate Settings response se we can test both individually.

Image description

Note we have correct data in Cooperate and wrong data in individual settings.
Let run the project and see.
Image

on executing any method the Company Options break because its being initialized in constructor of our controller. right now we are validating our Company Options at runtime.

Key Takeaways:

Utilize ".ValidateOnStart()" for compile time(when application starts) validation, especially on IOptions.
Utilize ".ValidateDataAnnotations()" for runtime validation, especially with IOptionsSnapshot and IOptionsMonitor.
By leveraging these validation techniques within the IOptions pattern, we can ensure robust configuration and mitigate errors that may arise during development and deployment.

Feel free to reach out for any inquiries or further discussions. Github Code Link link.

Top comments (2)

Collapse
 
evrai profile image
Evaldas Raisutis

"ValidateOnStart()" is this really compile time? Isn't it when the application starts / is bootstrapped?

Collapse
 
ahmedshahjr profile image
Ahmed Shah • Edited

yes when application starts => I mean compile time. let fix me it there also not to confuse others too.