Search code examples
asp.net-coreattributesasp.net-apicontroller.net-attributes

How can I both dependency injection and send value inside the attribute in .net core?


I want to decrpyt the request and encrypt the result by attribute. For this, I wrote the CheckFilter attribute below. But I need to do dependency injection to use IHashService service in it. I also want to send a value with attribute as it is used in the Get method. But I don't know how to do this.

 public class CheckFilter : Attribute, IResourceFilter
    {
        private readonly IHashService _hashService;

        public CheckFilter(IHashService hashService)
        {
            _hashService = hashService;
        }

        public void OnResourceExecuting(ResourceExecutingContext context)

        {
            //Decrypt 
        }

        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            //Encrypt
        }
    }
 [HttpGet]
 [CheckFilter("test")]
 public string Get(string request)
 {
      return "hello";
 }

Solution

  • If you want to get the service inside the filter attribute, you could use service location to resolve components from the built-in IoC container by using RequestServices.GetService.

    More details, you could refer to below codes:

    public class ThrottleFilterAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var cache = context.HttpContext.RequestServices.GetService<IDistributedCache>();
            ...
        }
        ...
    }