Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use dependency injection in my custom attribute?

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.

like image 789
alith Avatar asked Oct 22 '25 08:10

alith


1 Answers

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();
        }
    }
}
like image 128
RudimentalGhost Avatar answered Oct 23 '25 21:10

RudimentalGhost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!