Injecting into Custom Validation or Authorization Attributes in ASP.NET MVC

Yasser Shaikh
Jan 15, 2015 · 1 min read

Dependency Injection can be done when using Custom Validation or Authorization attributes in ASP.NET MVC. This can be achieved Ninject’s Property injection.

Here is an example of property injection. For a property to be injected it must be annotated with [Inject].

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);
}
}
More on "Injection of validators" can be read here.

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Yasser Shaikh

Written by

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade