When I check my ModelState["Email"].Errors
, I find the same validation error duplicated 3 times, and exactly 3 times for all my models, my models contain more than 3 properties.
I was wondering why the rules are getting executed three times.
I am using MVC 5, with Autofac. I can't find the mistake!
There are no errors, but I am concerned about performance if each property gets validated 3 times, some validations are complex and sometimes connect to the database.
Below is the code I use to register Validators
, Fluent Validation
and Autofac
.
builder.RegisterAssemblyTypes(System.Reflection.Assembly.Load("MyAssembly"))
.Where(t => t.Name.EndsWith("Validator"))
.AsImplementedInterfaces()
.InstancePerRequest();
builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>();
builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
Container = builder.Build();// Build !
// FluentValidation wire up to MVC
var fluentValidationModelValidatorProvider = new fluentValidationModelValidatorProvider()
{
AddImplicitRequiredValidator = false,
ValidatorFactory = new AutofacValidatorFactory()
};
//fluentValidationModelValidatorProvider.AddImplicitRequiredValidator = false;
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
The Model looks like this:
public class ContactInfoDTO
{
public int ID { get; set; }
public string Email { get; set; }
public string Email2 { get; set; }
public string PhoneNumber { get; set; }
public string PhoneNumber2 { get; set; }
public string EmergencyNumber { get; set; }
public string EmergencyPersonName { get; set; }
public ContactInfoDTO()
{
}
}
Thanks to everyone, for their support. Thanks to Mr. Jeremy Skinner, the owner of FluentValidation, has looked into it, the link to the solution below. it was my fault after all :)
https://github.com/JeremySkinner/FluentValidation/issues/362