Home > Software engineering >  Getting validators in classLibrary automatically with .net core 7 FluentValidation
Getting validators in classLibrary automatically with .net core 7 FluentValidation

Time:01-11

I am doing fluentValidation for my .net core web api project. I created a few classProjects in my project and made the configuration accordingly.

When there is a "Validations" folder under InventoryManagement.Services, validations do not work.

But when I import the "Validations" folder into "InventoryManagement.API" the validations work fine.

How can I overcome this situation?

So I want "Validations" files to stay in "InventoryManagement.Services".

InventoryManagement.API, Program.cs

Project Overall

Automatic validation is done with the following code block, but it only sees when it is in InventoryManagement.API, I want it to see "Validations" under "InventoryManagement.Services" instead

builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

Assembly.GetExecutingAssembly(); instead I just need to point to "InventoryManagement.Services" but how can I point it?

All my Validators have a structure like below

    public class CompanyUpdateDtoValidator : AbstractValidator<CompanyUpdateDto>
    {
        public CompanyUpdateDtoValidator()
        {
            RuleFor(x => x.Id).NotNull().WithMessage("{PropertyName} this field is required").NotEmpty().WithMessage("{PropertyName} this field is required.");
            RuleFor(x => x.Name).NotNull().WithMessage("{PropertyName} this field is required.").NotEmpty().WithMessage("{PropertyName} this field is required.");
            RuleFor(x => x.Description).NotNull().WithMessage("{PropertyName} this field is required").NotEmpty().WithMessage("{PropertyName} this field is required");
            RuleFor(x => x.BusinessCode).NotNull().WithMessage("{PropertyName} this field is required.").NotEmpty().WithMessage("{PropertyName} this field is required.");
        }
    }

CodePudding user response:

The Fluent team announced that they will remove the method you are using. It could be because of this.https://github.com/FluentValidation/FluentValidation/issues/1963 Can you add like this

builder.Services.AddFluentValidationAutoValidation()
                 .AddFluentValidationClientsideAdapters()
                 .AddValidatorsFromAssemblyContaining(typeof(Program));
  • Related