简体   繁体   中英

How to Resolve/inject Dependency for Attribute based class?

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
{
    // .......
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM