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库执行数据库相关的验证,或者是将此逻辑移动到其他位置的唯一解决方案(控制器操作,数据库本身,或者其他地方)?