Embedding DbContext in the FluentValidation Validator

I use the FluentValidation library to provide the only restriction on one of my models:

public class Foo { // No two Foos can have the same value for Bar public int Bar { get; set; } } public class FooValidator : AbstractValidator<Foo> { public FooValidator(ApplicationDbContext context) { this.context = context; RuleFor(m => m.Bar) .Must(BeUnique).WithMessage("Bar must be unique!"); } private readonly ApplicationDbContext context; public bool BeUnique(int bar) { return !context.Foos.Any(foo => foo.Bar == bar); } } 

The value of ApplicationDbContext is entered using StructureMap. To make sure the context is removed at the end of each request, I tried calling ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects() in the EndRequest handler for my application.

Unfortunately, it seems that the Application_EndRequest method is called before my validation class can complete its task, and the context is deleted by the time FooValidator.BeUnique executed.

Is there a better way to perform database-dependent validations using the FluentValidation library, or is it the only solution to move this logic to another location (either to the controller action, either directly to the database, or elsewhere)?

+8
dependency-injection asp.net-mvc-3 entity-framework structuremap fluentvalidation
source share
1 answer

Maybe the validator is not associated with the URL (but singleton), and it is not recreated / entered with a new context? In this case, it tries to use the highlighted context from the previous request.

+7
source share

All Articles