FluentValidation,验证程序的生命周期以及使用校验来检查了DB生命周期、程序、FluentValidation、DB

2023-09-04 13:20:22 作者:别留我独自一人

我用 FluentValidation 在我的 MVC4 项目。每一件事情完美的作品和它连接到我的的IoC ( StructureMap )。

I'm using FluentValidation in my MVC4 project. Every thing works perfectly and it's connected to my IoC (StructureMap).

我有2个问题:的

我应如何管理的生命周期中的我的验证?它是确定,使他们的单?或者它没有什么区别,我可以管理生命周期根据我的需求?什么是这里的最佳做法?

How should I manage lifecycle of my validators? Is it ok to make them singleton? or it makes no difference and I can manage lifecycle according to my needs? What is the best practice here?

FluentValidation 是很不错的。我一直在使用它的简单的验证(如:属性不为空,等)。我在考虑做一些 DB验证使用它(如:属性值是唯一即可。),我可以用我的传递库它< STRONG> StructureMap 并核对分贝值。 这是一个好主意?或者我应该在我的业务层实现这个逻辑并没有在我的IValidator?

FluentValidation is very good. I have been using it for simple validations (like: property is not empty, etc.). I'm thinking about doing some Db validations using it(like: property value is unique.) I can pass my repository to it using StructureMap and check values against Db. Is this a good idea? or should I implement this logic in my service layer and not in my IValidator?

如果你在类似的情况下使用它,什么是你的经验?

If you used it in similar scenarios, what was your experience?

推荐答案

我用FluentValidation好几年了,并要求,并计算出您的问题。

I've used FluentValidation for years now and have asked and figured out your questions.

个人创建验证程序的费用不是很昂贵,所以我没有让他们单身。我碰到的,需要访问的HttpContext需要一个文件上传与单身的问题。会发生什么事是第一次的HttpContext总是用于验证,而不是当前的。

我个人建议您不要使用单身

其实我做这一切的时候,我喜欢它。只是要牢记,任何依赖你注入应该是有效的。如果你的数据库查询执行全表扫描,需要30秒,那么这不是一个很好的经验。就像我上面说的,我一般注入的HttpContext检查,如果文件上传,和我通过一个DataContext来验证电子邮件是不是已被使用。

疯狂地使用这一点,FluentValidation的巨大优势,只要确定的依赖并不昂贵的问候时间和资源。