【问题标题】:Fluent Validation and IoC (Unique Field)Fluent Validation 和 IoC(唯一字段)
【发布时间】:2011-07-19 01:42:47
【问题描述】:

我正在使用 asp.net mvc 3 和 DDD 开发一个 Web 应用程序。对于我的域模型验证,我一直在使用 Fluent Validation。这是我的第一个流利验证项目,我仍在学习和建模实体。

我的实体客户有两个属性需要在我的系统中唯一,这些属性是电子邮件和 CPF(它是巴西文档,需要在所有系统中唯一)。我想知道,我该怎么做?

Soo,我的想法是,在我的 Customer 验证类中注入(通过构造函数)我的存储库,并通过自定义验证对其进行检查。验证将使用存储库检查,如果我的表中有记录,此电子邮件的 ID 不同(0 表示插入,真实 ID 表示更新......我不需要检查我正在更新的记录,因为它' d 总是正确的)。

我正在尝试这样的事情:

 public class CustomerValidator : AbstractValidator<Customer> {

     protected ICustomerRepository Repository { get; set; }

     // I intend to inject it by IoC with Unity.. is it possible ?
     public CustomerValidator(ICustomerRepository rep) 
     {
         this.Repository = rep;

         // other properties

         RuleFor(customer = customer.Email)
             .EmailAddress()
             .NotEmpty()
             .Must(email = { return Repository.IsEmailInUse(email, ?); });

         RuleFor(customer = customer.CPF)
             .NotEmpty()
             .Must(cpf = { return Repository.IsCPFInUse(cpf, ?); });

     }   }

我不知道是否有可能,在验证器中注入一个存储库,以及如何在 .Must 方法扩展中获取 Id ?或者有其他方法吗?

【问题讨论】:

    标签: asp.net-mvc validation dependency-injection domain-driven-design fluentvalidation


    【解决方案1】:
    RuleFor(customer => customer.Email)
        .EmailAddress()
        .NotEmpty()
        .Must((customer, email) => Repository.IsEmailInUse(email, customer.Id));
    
    RuleFor(customer => customer.CPF)
        .NotEmpty()
        .Must((customer, cpf) => Repository.IsCPFInUse(cpf, customer.Id));
    

    话虽如此,当您尝试插入记录并捕获适当的异常而不是在验证层中执行此操作时,系统本身(数据库?)也可以更有效地检查唯一性。原因是在 FluentValidation 检查唯一性和插入记录的实际时间之间可能会发生很多事情。

    【讨论】:

    • 感谢您的 awser Darin,但您的评论让我感到困惑。这个验证应该在另一个地方吗?在我的数据库中,我也有一些独特的约束来进行此验证,但我也需要通过域模型和 UI 来防止它,以避免异常,对吗?这个验证类在我域的类库项目中,对吗?或者我应该做一个验证层?我不太了解 DDD 和概念,我正在努力学习...谢谢 :)
    猜你喜欢
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多