将DbContext注入FluentValidation验证器

Jus*_*tch 10 structuremap entity-framework dependency-injection fluentvalidation asp.net-mvc-3

我正在使用FluentValidation库对我的某个模型强制执行唯一约束:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

ApplicationDbContext值是使用StructureMap注入.为了确保在每个请求结束时处理上下文,我试图调用我的应用程序ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()EndRequest处理程序.

不幸的是,似乎Application_EndRequest在我的验证器类能够完成其工作之前调用该方法,并且在FooValidator.BeUnique执行时间时处理上下文.

有没有更好的方法来使用FluentValidation库执行数据库相关的验证,或者是将此逻辑移动到其他位置的唯一解决方案(控制器操作,数据库本身,或者其他地方)?

Tz_*_*Tz_ 7

也许验证器不是http作用域(但是单例)并且不会重新创建/注入新的上下文?在这种情况下,它尝试使用先前请求中的已处置上下文.