views:

122

answers:

1

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!

A: 

According to this post by author of Ninject:

Field injection: Ninject 2’s injection is now driven by expression trees, and in .NET 3.5 there is no way to set field values with an expression tree. Since this is a bad practice anyway, I decided to cut it.

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:

public ApplicationIDValidAttribute()
{
  MyRepo = ServiceLocator.Current.GetInstance<IRepository<MyType>>();
}

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.

miensol
Thanks, Service Locator seems to be the way to go!
jaltiere