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
}
}
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.