Skip to content

Injection of validators

remogloor edited this page Mar 31, 2012 · 1 revision

Another new feature of the WebApi extension is the support for injection of validation attributes. But as with all other attributes it only allows property injection. The following example demonstrates how to create a zip code validation attribute that uses a service to check if the value is valid and that the zip code exists.

public class ZipCodeAttribute : ValidationAttribute
{
    [Inject]
    public IZipCodeService ZipCodeService { get; set; }
 
    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return true;
        }
 
        if ((value is string) && string.IsNullOrEmpty((string)value))
        {
            return true;
        }
 
        var zipCode = Convert.ToInt32(value);
        return this.ZipCodeService.IsValidZipCode(zipCode);
    }
}