RajGan
RajGan

Reputation: 861

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?

Upvotes: 3

Views: 6772

Answers (1)

bot_insane
bot_insane

Reputation: 2604

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.

Upvotes: 5

Related Questions