1

I am creating the following attribute class in an ASP.NET Core 6 Web API.

I need to make a database call from this class and want to get dbContext which is already registered with dependency container.

How do I inject the dbcontext into my customAuthorization class ?

[AttributeUsage(AttributeTargets.Class)]
public class CustomAuthorization : Attribute, IAuthorizationFilter
{
   private readonly IServiceProvider _serviceProvider;
    
   public CustomAuthorization(IServiceProvider serviceProvider)
   {
          _serviceProvider = serviceProvider;
   }


   public void OnAuthorization(AuthorizationFilterContext filterContext)
   {
       ...................
   }

}

[CustomAuthorization()]
public class OrganizationController : CustomControllerBaseClass
{
    // .......
}
1
  • 1
    The issue is not in the filter calls but with the Declaration of Attribute on OrganizationController , it expects IServiceProvider to be passed in from Customauthorixation class Commented Jan 29, 2023 at 18:38

1 Answer 1

2

IAuthorizationFitler has a OnAuthorization(AuthorizationFilterContext filterContext) method, doesn't it?
You could use the filterContext.HttpContext.ServiceProvider.GetRequiredService....

[AttributeUsage(AttributeTargets.Class)]
public class CustomAuthorization : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext filterContext)
    {
        var context = filterContext.HttpContext.ServiceProvider.GetRequiredService<Your_DbContext>();  
        ...                                      
    }
}

Though, I don't know the scope of the AuthorizationFilter, whether it's singleton, scoped or transient: if it's singleton, you could create a scope on your own:

using(var scope = filterContext.HttpContext.ServiceProvider.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<Your_DbContext>();  
    ...                                      
}  

I don't know whether I'm wrong somewhere OR there is an easier approach, but this is my quick response.

Sign up to request clarification or add additional context in comments.

3 Comments

The signature for OnAuthorization is different in .net public void OnAuthorization(AuthorizationFilterContext filterContext) { }
Actually this link helped stackoverflow.com/a/69310490/1764116
@nss Just a typo, sorry. Edited!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.