简体   繁体   English

避免在FluentValidations中重复

[英]Avoiding duplication in FluentValidations

I have a validator for a CreateRequest and another for UpdateRequest . 我有一个用于CreateRequest的验证器,另一个用于UpdateRequest的验证器。

I soon discovered that they are the same. 我很快发现它们是相同的。 The only difference is that one has an Id ( UpdateRequest ). 唯一的区别是一个具有Id( UpdateRequest )。

The validations are the same, to the same properties, but the entities are different. 验证是相同的,具有相同的属性,但是实体不同。

How can I avoid duplicating the rules? 如何避免重复规则?

Currently I have 目前我有

public class CreateValidator : AbstractValidator<CreateRequest> 
{
     RuleFor(p => p.Prop1)...  // Rule 1
     RuleFor(p => p.Prop2)...  // Rule 2
     RuleFor(p => p.Prop3)...  // Rule 3
}

public class UpdateValidator : AbstractValidator<UpdateRequest> 
{
     RuleFor(p => p.Id)...     // Rule 0
     RuleFor(p => p.Prop1)...  // Rule 1
     RuleFor(p => p.Prop2)...  // Rule 2
     RuleFor(p => p.Prop3)...  // Rule 3
}

They are the same except for the Rule 0. 除了规则0外,它们相同。

Can I avoid duplication? 我可以避免重复吗?

  1. Make sure that your CreateRequest and UpdateRequest implement the same interface of are inherited from some base class(or one from another). 确保您的CreateRequestUpdateRequest实现相同的接口,该接口是从某个基类(或从另一个基类)继承的。

     public CreateRequest: Request{...} public UpdateRequest: Request{...} 
  2. Create a generic validator class with restricted generic type parameter. 创建具有受限通用类型参数的通用验证器类。

     public RequestValidator: AbstractValidator<T> where T: Request { RequestValidator() { RuleFor(p => p.Prop1)... // Rule 1 RuleFor(p => p.Prop2)... // Rule 2 RuleFor(p => p.Prop3)... // Rule 3 } } 
  3. Create actual validator using inheritance. 使用继承创建实际的验证器。

     public CreateRequestValidator: RequestValidator<CreteRequest> { CreateRequestValidator() { } } public UpdateRequestValidator: RequestValidator<UpdateRequest> { UpdateRequestValidator() { RuleFor(p => p.Id)... } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM