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 'SomeDbContext' from singleton 'Microsoft.AspNetCore.Authorization.IAuthorizationHandler'.</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>();
...
}