Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Dependencies into Validation Attribute using ASP.NET Core's WebAPI

I'm building a Custom Validation Attribute in ASP.NET Core WebAPI. I need to access IDataProtector in my validator and another service I'm using to access the database. I've searched and wasn't ab;e to find any documentation for this. ActionFilters have the option of using ServiceFilter but there doesn't seem to be any option for Validation Attribute. Any ideas?

like image 905
Madhav Shenoy Avatar asked Sep 21 '16 23:09

Madhav Shenoy


2 Answers

Use the GetService() method of the ValidationContext to get your database. i.e.

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
  MyDbContext db = (MyDbContext) validationContext.GetService(typeof(MyDbContext));
  //...
}
like image 107
Richard Avatar answered Sep 18 '22 10:09

Richard


You can override IsValid method and use validationContext to resolve dependency:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
{
    var service = (IExternalService) validationContext.GetService(typeof(IExternalService));
    // use service
}
like image 25
alireza.salemian Avatar answered Sep 18 '22 10:09

alireza.salemian