EF Core DB Context Injection In Custom Authorization Handler

asp.net-core c# entity-framework-core

Question

I need to use entity framework in my custom authorization handler. But it's not working. It fails on runtime. I am getting this error in response body:

<h2 class="stackerror">InvalidOperationException: Cannot consume scoped service &#x27;SomeDbContext&#x27; from singleton &#x27;Microsoft.AspNetCore.Authorization.IAuthorizationHandler&#x27;.</h2>

I can't inject DB Context like this. How can I use db context in my custom authorization handler?

In my custom authorization handler class:

public class CustomAuthorizationHandler : AuthorizationHandler<CustomAuthRequirement>
{
    private readonly SomeDbContext _dbContext;

    public CustomAuthorizationHandler(SomeDbContext context)
    {
        _dbContext = context;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomAuthRequirement requirement)
    {
        ...

        //Some datatable read operations with _dbContext

        ...
    }
}

In my Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<SomeDbContext>(options =>
              options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

        services.AddSingleton<IAuthorizationPolicyProvider, CustomAuthPolicyProvider>();

        services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();

        ...
    }
1
0
10/9/2019 12:49:35 AM

Accepted Answer

You could just inject IServiceProvider serviceProvider into the CustomAuthorizationHandler .Try to use below code:

public class CustomAuthorizationHandler : AuthorizationHandler<CustomAuthRequirement>
{
    private readonly IServiceProvider _serviceProvider;

    public CustomAuthorizationHandler (IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   CustomAuthRequirement requirement)
    {

        using (var scope = _serviceProvider.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<SomeDbContext>();

            //...
        }
    }
}
1
10/9/2019 8:28:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow