Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 Fluent Validation Constructor hit multiple times per request

I have an ASP.NET MVC3 website setup using fluent validation and ninject. The validation code is working. However, I set a break point in the validation class constructor and I noticed that when I request my view that uses the validation the constructor gets hit multiple times. Based on very basic testing it seems that the number of times the constructor is hit is equal to the number of properties that exist on the object. Has anyone else come across something similar? Or can someone shed more insight on how this type of validation works behind the scenes? -Thanks

Here is the constructor...

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}

Here are the libraries/resources that I am using (I just got the NuGet packages and configured everything based on the info from the two links below):

http://fluentvalidation.codeplex.com/wikipage?title=mvc https://github.com/ninject/ninject.web.mvc.fluentvalidation

like image 213
Zoran Avatar asked Oct 18 '11 15:10

Zoran


1 Answers

I figured out how to prevent this issue. Even though this solves my issue, I would like input from others on whether there are any consequences in doing this?

So on the second link you will see instructions on how to set up Ninject.

On the second step you need to apply the "InRequestScope()" extension method. Then the constructor will only be hit once per http request that uses your validator. That obviously means that only one instance of the validator object is created per http request, which makes sense to me. I don't know if there are any consequences to using this solution?

Bind(match.InterfaceType).To(match.ValidatorType).InRequestScope();
like image 115
Zoran Avatar answered Nov 07 '22 07:11

Zoran