开发者

Fluent Validation and IoC (Unique Field)

开发者 https://www.devze.com 2023-03-21 19:21 出处:网络
I\'m developing a web application with asp.net mvc 3 and DDD. For my domain model validation, I\'ve been using Fluent Validation. It\'s my first project with fluent validation and I\'m still learning

I'm developing a web application with asp.net mvc 3 and DDD. For my domain model validation, I've been using Fluent Validation. It's my first project with fluent validation and I'm still learning and modeling the entities.

My entity Customer has two properties that need to be unique in my system, these properties are Email and CPF (it's a Brasilian document and need to be unique in all system). I would like to know, how can I to it ?

Soo, my ideia is, inject (by constructor) my repository in my validation class of Customer and check it by a custom validation. The validation would be check using the repository if is there record in my table with this email different of an Id (0 for inserts and real Id for updates... I don't need to check the record I'm updating because it'd always be true).

I`m trying something like this:

 public class CustomerValidator : AbstractValidator<Customer> {

     protected ICustomerRepository Repository { get; set; }

     // I intend to inject it by IoC with Unity.. is it possible ?
     public CustomerValidator(ICustomerReposi开发者_StackOverflowtory 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, ?); });

     }   }

I don't know if is possible, inject a repository inside the validator, and how could I get the Id in the .Must method extension ? Or is there another method to do it?


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));

This being said, checking for uniqueness could also be more efficiently done by the system itself (database?) at the moment you are trying to insert the record and catch the appropriate exception instead of doing this in the validation layer. The reason for this is that between the time your FluentValidation checked for uniqueness and the actual time a record is inserted many things could happen.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号