使用Fluent验证器

时间:2017-10-01 12:10:46

标签: c# .net fluentvalidation

我想尝试.NET FluentValidation库,以便在即将开展的项目中进行表单输入验证。在查看文档时,我遇到了这个:

关于效果的说明

Instantiation of validators is an expensive process due to the expression tree compilation and parsing within the RuleFor definitions. Because of this, it's recommended that you use validator instances as singletons- once instantiated they should be cached and reused, rather than being instantiated multiple times. Validators do not contain any shared state, so it should also be safe to reuse them in multithreaded scenarios too.

The best approach to caching the validator instances would be to use an IoC container (eg, StructureMap) to manage the instance lifecycles.

我不知道这意味着什么?有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

他们建议只在应用程序启动时(急切)或首次需要(懒惰)时实例化一次验证器的实现。实现此目的的最常见方法是使用单例模式。有关C#中此特定模式的更多信息,您可以转到C# in Depth - Singletons

管理验证器的更简单方法是使用IoC容器,例如Ninject,Castle Windsor,Unity等,因为它们允许您将依赖注册指定为具有单身生活方式和