How to get property injection in Ninject for ValidationAttribute in MVC?

I have the verification attribute set, where I need to get into the database in order to perform the verification. I tried to configure the property attachment in the same way as in other places in the project, but it does not work. 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 more note: I have a Ninject kernel configured to enter non-public properties, so I don't think this is a problem. I am using Ninject 2, MVC 2 and the MVC 2 version for Ninject.Web.MVC.

Thank!

+3
source share
2 answers

According to this post by Ninject:

: Ninject 2s .NET 3.5 . , , .

-, , MVC2 Inversion Control Container, Ninject , .

ServiceLocator :

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

Service Locator, codeplex. , Service Locator, .

+2

, -, ninject support property injection

, .

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

Source: https://habr.com/ru/post/1743402/


All Articles