I am using the FluentValidation library to enforce a unique constraint 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 ApplicationDbContext
value is injected using StructureMap. To make sure that the context is disposed of at the end of every request, I attempted to call ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()
in the EndRequest
handler for my application.
Unfortunately, it appears as though the Application_EndRequest
method is called before my validator class is able to do its job and the context is disposed by the time FooValidator.BeUnique
is executed.
Is there a better way to perform database-dependent validations with the FluentValidation library, or is the only solution to move this logic elsewhere (either to the controller action, the DB itself, or maybe elsewhere)?