自定义授权处理程序中的 EF Core DB 上下文注入

Fur*_*ara 4 c# entity-framework-core asp.net-core

我需要在自定义授权处理程序中使用实体框架。但这不起作用。它在运行时失败。我在响应正文中收到此错误:

<h2 class="stackerror">InvalidOperationException: Cannot consume scoped service &#x27;SomeDbContext&#x27; from singleton &#x27;Microsoft.AspNetCore.Authorization.IAuthorizationHandler&#x27;.</h2>
Run Code Online (Sandbox Code Playgroud)

我无法像这样注入数据库上下文。如何在自定义授权处理程序中使用数据库上下文?

在我的自定义授权处理程序类中:

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

        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的 Startup.cs 中:

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

        services.AddSingleton<IAuthorizationPolicyProvider, CustomAuthPolicyProvider>();

        services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();

        ...
    }
Run Code Online (Sandbox Code Playgroud)

Rya*_*yan 7

您可以直接注入。IServiceProvider serviceProvider尝试 CustomAuthorizationHandler使用以下代码:

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>();

            //...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)