This article will explain how to register fluent validators in dependency injection containers. For demonstrating it is going to use the .NET’s default dependency injection container.
Registering Specific Validator Type
Registering a validator in dependency container is same as registering any other type. We can register the
IValidator<T> where T is the type that we have used for a validator as the construct. This can be done in the API startup configurations.
In previous articles, we have used a
StudentValidator class to validate the Student type.
The code snippet given below shows how to register
StudentValidator in the container and then how it can be used inside the controller.
Registering All Validators In One Go
There is also another simpler way of adding all the validators in one go. For that, we need to make sure that we have added FluentValidation.DependencyInjectionExtensions package to the project. The command given below can be used to add the NuGet package to the project.
dotnet add package FluentValidation.DependencyInjectionExtensions
After this NuGet package is added, we can open Program.cs file. I don’t have Main method or Startup class here as I chose to use top level statements in the project. But the idea is to call method –
AddValidatorsFromAssemblyContaining – on an instance of
IServiceCollection, as shown in the code snippet given below. If you have Startup file, then you can use ConfigureServices method for calling this method.
As the code snippet shows, this call needs a parameter of type – System.Type. The framework will try to get all the validators from the assembly in which the provided type is available and all those validators would be registered in the DI container. There are other overloads available too. One overload also allows to set the lifetime (i.e. Singleton, Scoped or Transient) for the validators as shown in the code snippet
The code snippet also shows how the
StudentValidator can be used inside the controller.
Which scope should be preferred ?
Generally, it is recommended to set the lifetime for the validators to be Scoped or Transient. As per documentation, it is better to always go for Transient scope.
If the validator scope is set to be Singleton, then we should try to avoid injecting any Transient dependencies in the validator. Otherwise, it may be difficult to debug the issues related to singleton scoped objects having non-singleton dependencies.
I hope you find this information helpful. Let me know your thoughts.