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?

To be honest, I have no idea how to solve this problem.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With