FluentValidation and Entity Framework Lookups

1.1k views Asked by At

I have an ASP.NET MVC application with Entity Framework. This application scopes the DbContext to the current HTTP request, but also accounts for out of band requests, returning a new DbContext for every request. I have the default Fluent validation provider registered like:

FluentValidationModelValidatorProvider.Configure();

In the constructor I have some dependencies on Entity Framework:

public class SomeValidator : AbstractValidator<Customer>
{
   public SomeValidator()
   {
     private _refService = //Get IReferenceDataService through DI container
     Dim refID = _refService.GetID(details of value to find ID for);

       RuleFor((m) => m.Field).Must((o, v) =>
            {
                if (v == reID)
                  return false;
                else
                    ...
            }).WithMessage("..");
   }
}

The call to return a value to refID hits the database using Entity Framework. Does the constructor run during the HTTP request, thus using my cached EF container for the current request, or will this happen in an out-of-bound fashion? I'm not sure when the validator gets initialized...

1

There are 1 answers

0
Matt Whetton On

Generally speaking the validator will be constructed lazily (i.e. the first time you need it), and will then remain in your DI container for future use. So it wouldn't be scoped to the http request.