Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .net Core Fluentvalidation manual validation get validator class instance

I am trying to get the validator class instance instead of manually initiating in my method.

I am using Asp .net core webapi 2 where I register my validator in startup class using

services.AddMvc().AddFluentValidation().

In one of my action method, I had to validate a ruleset. So I am creating my validator class locally like

var validator = new MyClassValidator()
var result = validator.Validate(obj,ruleSet: "RulesetName");

I am trying to avoid this statement var validator = new MyClassValidator(). I would like to use IOC and get an instance. Any help?

like image 532
RajGan Avatar asked Jun 14 '26 13:06

RajGan


1 Answers

It is required to register MyClassValidator in IoC container manually:

services.AddTransient<IValidator<T>, MyClassValidator>();

As documentation states, you don't need to use an instance of this class manually, FluentValidation will validate it automatically.

FluentValidation can be integrated with Asp.NET Core. Once enabled, MVC will use FluentValidation to validate objects that are passed in to controller actions by the model binding infrastructure.

Anyway, if you need to use this class manually, you can simply add a parameter of type IValidator<T> to your desired constructor.

like image 82
bot_insane Avatar answered Jun 16 '26 04:06

bot_insane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!