将 DbContext 注入 FluentValidation 验证器
我正在使用 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);
}
}
使用 StructureMap 注入 ApplicationDbContext
值。为了确保在每个请求结束时释放上下文,我尝试在应用程序的 EndRequest
处理程序中调用 ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()
。
不幸的是,似乎在我的验证器类能够完成其工作之前就调用了 Application_EndRequest 方法,并且在执行 FooValidator.BeUnique 时上下文已被释放。
是否有更好的方法来使用 FluentValidation 库执行依赖于数据库的验证,或者是将这个逻辑移到其他地方(控制器操作、数据库本身或其他地方)的唯一解决方案?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许验证器不是 http 范围的(而是单例的)并且它没有用新的上下文重新创建/注入?在这种情况下,它尝试使用先前请求中已处理的上下文。
Maybe the validator is not http scoped (but singleton) and it is not recreated/injected with a new context? In this case it tries to use a disposed context from a previous request.