.Net Core 依赖注入而不在构造函数中传递依赖

.Net Core Dependency Injection without passing Dependency in Constructor

我正在实施自定义 [Authorize] 属性。在 IdentityAuthorizeFilter Class 的 OnAuthorization 方法中,我需要访问 DBContext 以执行数据库检查。我无法在 Class 的构造函数中传递上下文。如何访问此 class 中的 DBContext?

Startup.cs

public void ConfigureServices(IServiceCollection services)
{            
            services.AddDbContext<SecureContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("SecureContext")));
}

自定义授权:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class IdentityAuthorizeAttribute : TypeFilterAttribute
{
    public IdentityAuthorizeAttribute(string permissions)
        : base(typeof(IdentityAuthorizeFilter))
    {
        Arguments = new object[] { permissions };
    }
}

public class IdentityAuthorizeFilter : IAuthorizationFilter
{

    public IdentityAuthorizeFilter(string permissions) => Permissions = permissions;
    public string Permissions { get; set; }


    [Authorize]
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var claims = context.HttpContext.User.Claims.ToList();
        var auth = context.HttpContext.User.Identity.IsAuthenticated;

        //Access DB Context
        
        if (!isAuthorized)
            context.Result = new UnauthorizedResult();
    }
}

这个有用吗?

var dbContext = context.HttpContext.RequestServices.GetRequiredService<SecureContext>();

我不确定它是否会,但我使用 Microsoft 的 AddMicrosoftIdentityWebApp 方法做了类似的事情,如下所示:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(
        options =>
        {
            configuration.Bind("AzureAD", options);
            options.Events ??= new OpenIdConnectEvents();
            options.Events.OnTokenValidated += async tokenValidatedContext =>
            {
                var dbContext = tokenValidatedContext.HttpContext.RequestServices.GetRequiredService<dbContext>();
                // Do stuff with db context here
            };
        });