entity-framework – 将DbContext注入FluentValidation验证器
发布时间:2020-05-24 10:28:36 所属栏目:asp.Net 来源:互联网
导读:我正在使用FluentValidation库对我的某个模型强制执行唯一约束: public class Foo { // No two Foos can have the same value for Bar public int Bar { get; set; }}public class FooValidator : AbstractValidatorFoo {
|
我正在使用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库执行数据库相关的验证,或者是将此逻辑移动到其他位置的唯一解决方案(控制器操作,数据库本身或其他地方)? 解决方法也许验证器不是http作用域(但是单例)并且不会重新创建/注入新的上下文?在这种情况下,它尝试使用先前请求中的已处置上下文.(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – LINQ:自定义列名
- asp.net – IIS 7的最大默认POST请求大小 – 如何增加64kB
- asp.net – 通过Ajax Post – MVC3更新模型更改视图
- ASP.NET Web API,Web服务发现和客户端创建
- asp.net – 从域到www.domain的全局301重定向
- asp.net – ReportViewer超时,尽管超时设置
- 收藏的asp.net文件上传类源码
- asp.net-mvc – 保持viewdata在RedirectToAction
- ASP.NET Core 2.0 Web API响应缓存
- asp.net-web-api – owin cors或web api cors
推荐文章
站长推荐
- asp.net – C#:GDI:使用位图的保存方法过度写入
- asp.net-mvc – ASP.NET MVC 6中的文件IO Close(
- asp.net-mvc – 如何在ASP.NET MVC中传递页面的元
- asp.net – 为什么我需要PUT或DELETE Http Verbs
- asp.net-ajax – ScriptManager.RegisterClientS
- 在为ASP.net构建期间缩小内联JavaScript?
- asp.net-mvc – 如何在View中获取当前的url值
- asp.net – 在telerik网格的列中使用控件
- 使T4MVC与ASP.NET 5一起使用
- asp.net – MVC控制器和视图应该有1到1的关系吗?
热点阅读
