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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With