1

I have a custom attribute in asp.net mvc and use structure map. how can I inject ContextDB into the custom ValidationAttribute?

[AttributeUsage(AttributeTargets.Property)]
public class CustomValidationAttribute : ValidationAttribute
{
    public ContextDB _Context { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        Settings settings = new Settings(_Context);

        // Checking...

        return ValidationResult.Success;
    }
}

my code doesn't work, _Context is null. what should I do?

Thanks.

Saeid Mirzaei
  • 950
  • 2
  • 18
  • 48

1 Answers1

4

If you have registered your DI to MVC you could use MVC's dependency resolver everywhere.

public class CustomValidationAttribute : ValidationAttribute
{
     private ContextDB _context { get; set; }

     public CustomValidationAttribute()
     {
         // assuming you have a IContextDB interface which mapped to 
         // ContextDB in your StructureMap
          _context =DependencyResolver.Current.GetService<IContextDB>();
     }
     // rest of your code
}

For more advanced scenario look at Setter Injection concept also.

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56