Fur*_*ara 4 c# entity-framework-core asp.net-core
我需要在自定义授权处理程序中使用实体框架。但这不起作用。它在运行时失败。我在响应正文中收到此错误:
<h2 class="stackerror">InvalidOperationException: Cannot consume scoped service 'SomeDbContext' from singleton 'Microsoft.AspNetCore.Authorization.IAuthorizationHandler'.</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)
您可以直接注入。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)
| 归档时间: |
|
| 查看次数: |
2120 次 |
| 最近记录: |