开发者

How do I get property injection working in Ninject for a ValidationAttribute in MVC?

开发者 https://www.devze.com 2022-12-28 10:41 出处:网络
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 workin

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 : Validation开发者_开发问答Attribute
{
    [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:

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.


I think you just need a getter and setter on your repo member, ninject support property injection

Just change you code to this and it should work.

[Inject]
public IRepository<MyType> MyRepo{
    get; set;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消