All Articles

FluentOptions: An extension to FluentValidation for your configuration validation

Intro

Recently I had to get my configuration validated on startup. All resources I could find were related to IValidatable and IValidatableObject with the good ol’ data annotations, but what about us who love FluentValidation? After some research I found IStartupFilter which seemed to do exactly what I needed for my purpose.

Implementation

Looking at the example from Microsoft documentation IStartupFilter it seems simple enough. All we have is a Configure method where we’ll place our FluentValidation execution.

filter_code

IStartupFilter

All we have to do is inject the validator and the options to the filter constructor. Once we have access to the validator, we can simply call Validate and pass the Options instance which is supposed to get validated. Usually we’d like to abort the startup of the service if a configuration is misconfigured, so we will throw an Exception if the user wants it. If not, we’ll just log the error messages.

filter_code

Extension method

Let’s add an extension method which allows us to add the required startup filter to the container.

extension_code

Pretty simple, isn’t it? We just get the validator, options and logger instance from the container and then build our filter.

Usage

result_code

Let’s say our appsettings.json looks like this and the email address is malformed:

app_settings

When you start the service, the validation will run and the malformed property will be shown.

error_console

Notes

At the moment I am not happy because I am injecting multiple IStartupFilter instances. I would prefer having one IStartupFilter which would then iterate through all the available options validators. If you have a suggestion, feel free to open a PR request.

Link

https://github.com/atresnjo/FluentOptionsValidation