I created a custom Authorization attribute and I want to use a service in it but I'm not sure how to use it there as dependency injection doesn't work well.
public class MyAuthorizationAttribute : Attribute, IAuthorizationFilter
{
public static Func<IMyService> MyService { get; set; }
public MyAuthorizationAttribute()
{
Console.WriteLine("Attribute Initialized");
}
public async void OnAuthorization(AuthorizationFilterContext context)
{
await MyService.Validate(...);
Console.WriteLine("OnAuthorization");
}
}
Trying with a delegate function but no success as well (MyService is always null), any ideas? And is the correct use of this?
I would like to use this attribute like this :
[HttpGet]
[MyAuthorizationAttribute]
[Route(...)]
public async Task<ActionResult> GetMyMethodAsync()
{
//...
}
I just want to avoid to use the same code in every endpoint.
This is how the service is registered :
builder.Services.AddScoped<Func<IMediator>>(x => x.GetRequiredService<IMediator>);