FluentValidation as a Service

I am using FluentValidation 2 to validate some objects. I would like to create IValidationServiceone that I can transfer to other services so that they can perform validation. I would like to expose this as follows:

public interface IValidationEngine
{
    IEnumerable<ValidationError> Validate<T>(T entity);
}

Where ValidationErroris a class that encapsulates my validation errors. Ideally, I would not expose a specific validator to one of my services (for example, OrderValidator). I would like the validation service to be able to build / find the correct validator. Does FV have something built-in to search for a validator for a specific type (and it internally caches)? Or do I need to go through the route IValidatorFactoryand then connect each validator to the IoC container?

+3
source share
1

IValidatorFactory. Ninject, IoC .

public interface IValidationService
{
    IEnumerable<ValidationError> Validate<T>(T entity)
        where T : class;
}

public class FluentValidationService : IValidationService
{
    private readonly IValidatorFactory validatorFactory;

    public FluentValidationService(IValidatorFactory validatorFactory)
    {
        this.validatorFactory = validatorFactory;
    }

    public IEnumerable<ValidationError> Validate<T>(T entity)
        where T : class
    {
        var validator = this.validatorFactory.GetValidator<T>();
        var result = validator.Validate(entity);
        return result.Errors.Select(e => new ValidationError(e.PropertyName, e.ErrorMessage));
    }
}

// Then implement FV IValidatorFactory:

public class NinjectValidatorFactory : ValidatorFactoryBase
{
    private readonly IKernel kernel;

    public NinjectValidatorFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        return kernel.TryGet(validatorType) as IValidator;
    }
}

// I then wire both of these in a Ninject Module:

public class ValidationModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<IValidationService>().To<FluentValidationService>().InRequestScope(); // Specific to MVC.
        this.Bind<IValidatorFactory>().To<NinjectValidatorFactory>().InRequestScope();
    }
}

// Then I can use it inside a service:

public class FooService
{
    private readonly IValidationService validationService;

    public FooService(IValidationService validationService)
    {
        this.validationService = validationService;
    }

    public bool Add(Foo foo)
    {
        if(this.validationService.Validate(foo).Any())
        {
            // Handle validation errors..
        }

        // do other implementation details here.
    }
}
+8

Source: https://habr.com/ru/post/1788047/