1

How can i use dependency injection in my custom attribute? Hi,i am writing an custom attribute and i need use some interface method on my custom attribute . so need to build contractor for inject my service(interface), if i do this when I want to use my attribute, it requires an input of that interface type, what can i do?

enter image description here

To be honest, I have no idea how to solve this problem.

alith
  • 11
  • 2
  • 2
    You should prevent doing dependency injection into attributes completely. Credits of all info here https://stackoverflow.com/a/29916075/14322498 – Leandro Toloza Oct 25 '22 at 14:04
  • Strictly speaking, we cannot use dependency injection to inject a dependency into an attribute. You can refer to this [link](https://stackoverflow.com/questions/4102138/how-to-use-dependency-injection-with-an-attribute) to learn more. – Xinran Shen Oct 26 '22 at 08:08

1 Answers1

2

You can use TypeFilter coupled with an attribute using normal DI with nothing special see example(async) below

Controller method decorated with attribute:

[TypeFilter(typeof(TestAttribute))]
public async Task CreateAsync()
{
    //your method here
    return null;
}

Attribute:

public class TestAttribute : Attribute, IAsyncAuthorizationFilter
{
    private readonly IIdentityService _identityService;

    public TestAttribute(IIdentityService identityService)
    {
        _identityService = identityService;

    }
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        ApplicationUser user = await _identityService.CurrentUser();

        if (user.TestId == null)
        {
            context.Result = new UnauthorizedResult();
        }
    }
}