I have a validation attribute set up where I need to hit the database to accomplish the validation. I tried setting up property injection the same way I do elsewhere in the project but it’s not working. What step am I missing?
public class ApplicationIDValidAttribute : ValidationAttribute
{
[Inject]
protected IRepository<MyType> MyRepo;
public override bool IsValid(object value)
{
if (value == null)
return true;
int id;
if (!Int32.TryParse(value.ToString(), out id))
return false;
// MyRepo is null here and is never injected
var obj= MyRepo.LoadById(id);
return (obj!= null);
}
One other thing to point out, I have the Ninject kernel set up to inject non-public properties, so I don’t think that is the problem. I’m using Ninject 2, MVC 2, and the MVC 2 version of Ninject.Web.MVC.
Thanks!
According to this post by author of Ninject:
Secondly as far as I know in MVC2 by default attributes are not constructed via Inversion of Control Container, so even if Ninject would support field injection this still would not work.
One simple solution would be to use ServiceLocator in your attribute constructor like this:
If you are not familiar with Service Locator you can find information about it on codeplex.
Second slightly harder approach, which does not imply use of Service Locator is described here.