Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IValidatableObject and Dependency Injection support

On my ASP.NET MVC 3 project, I have implemented the repository pattern inside a seperate class library project.

Also I am using EF as ORM. I have also implemented some model validation with IValidatableObejct interface. Here is how it looks like :

[MetadataType(typeof(AccommPropertySeasonPeriodAlias.MetaData))]
public partial class AccommPropertySeasonPeriodAlias : IValidatableObject {

    private class MetaData {

        [StringLength(5), Required]
        [Display(Name = "Period Alias Name")]
        public string AccommPropertySeasonPeriodAlias1 { get; set; }
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {

        var repo = new AccommPropertySeasonPeriodAliasRepository();

        if (repo.GetAll(this.AccommPropertySeasonID).
            Where(x => x.AccommPropertySeasonPeriodAlias1 == this.AccommPropertySeasonPeriodAlias1) != null)

            yield return new ValidationResult("Alias Name needs to be unique");
    }
}

As you see, from now on, my model completely tightly-coupled because I have used AccommPropertySeasonPeriodAliasRepository class directly instead of using IAccommPropertySeasonPeriodAliasRepository.

What is the way of doing this right so that my model can be, well, (not sure if this is the right word) fake-able for unit testing?

like image 449
tugberk Avatar asked Nov 10 '11 16:11

tugberk


1 Answers

Validation logic can be injected using MVC's built in resolver.

See the usage with the ModelValidatorProvider which is resolved using the registered container in MVC.

ASP.NET MVC 3: Validating model when information external to the model is required

like image 194
Adam Tuliper Avatar answered Oct 05 '22 22:10

Adam Tuliper