Validate method of AbstractValidator never is called using ValidatorFactoryBase

Question!

I implemented my Validations using FluentValidation and Autofac.

The CreateInstance is called, but the method Validate of AbstractValidator not, so my model not is validate using my rules.

Debugging: In CreateInstance the correct AbstractValidator is returned.

But I put breakpoints in Validate and not is called.

Any Ideia?

My code:

public class AutofacValidatorFactory : ValidatorFactoryBase
{
    private readonly IComponentContext _context;

    public AutofacValidatorFactory(IComponentContext context)
    {
        _context = context;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        object instance;
        if (_context.TryResolve(validatorType, out instance))
        {
            var validator = instance as IValidator;
            return validator; //UsuarioCadastrarValidator is returned 
        }

        return null;
    }
}

public class UsuarioCadastrarValidator : AbstractValidator<UsuarioCadastrarVM>
{
    public UsuarioCadastrarValidator()
    {
        RuleFor(a => a.Nome).NotEmpty();

        RuleFor(a => a.Nome).Length(4, 200);

        ...
    }

    public override ValidationResult Validate(UsuarioCadastrarVM instance)
    {
        return base.Validate(instance); //breakpoint here not is called
    }

    public override IValidatorDescriptor CreateDescriptor()
    {
        return base.CreateDescriptor(); //breakpoint here IS called
    }

    public override ValidationResult Validate(ValidationContext<UsuarioCadastrarVM> context)
    {
        return base.Validate(context); //breakpoint here not is called
    }

    public override Task<ValidationResult> ValidateAsync(ValidationContext<UsuarioCadastrarVM> context, CancellationToken cancellation = default(CancellationToken))
    {
        return base.ValidateAsync(context, cancellation); //breakpoint here not is called
    }
}


Answers

In UsuarioCadastrarVM I have a property CargoId with type int

The problem was CargoId is a integer, so the MVC is not able to bind my post to my ViewModel, because in my tests I sended a empty value, if I send a value to CargoId or change to nullable (int?) the validation works well.



The "using" keyword makes a member of an inherited class visible, and resolvable, in the scope of its subclass. So, to make the privately-inherited member available to B's subclasses:

class A {

protected:

    void foo() {}
};

class B : private A {

protected:

    using A::foo;
};

class C : public B {

    void bar()
    {
        foo();
    }
};


An item of type undefined (and it is a type) has no length property - only items of type string and array do. Therefore, as @redneb notes, extend your condition to check for a non-falsy value before checking length.

if (myVar && myVar.length) { ... }
By : Utkanos


This video can help you solving your question :)
By: admin