You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7 Blazor WASM中OpenIdConnect事件的依赖注入方法问询

在OpenIdConnect登出事件中获取注入对象的方案

下面是几种在OpenIdConnect事件中获取依赖注入对象(比如IGrainFactory)的可行方法:

方法1:从事件上下文的HttpContext获取服务

OpenIdConnect各事件的上下文对象(比如RemoteSignOutContext、RedirectToIdentityProviderForSignOutContext)都包含HttpContext,通过HttpContext.RequestServices就能拿到已注册的服务实例:

.AddOpenIdConnect("oidc", options =>
{
    // 其他OIDC配置项...

    options.Events = new OpenIdConnectEvents
    {
        OnRemoteSignOut = async context =>
        {
            // 获取IGrainFactory实例
            var grainFactory = context.HttpContext.RequestServices.GetRequiredService<IGrainFactory>();
            
            // 调用Grain的停用逻辑,这里假设用用户标识作为Grain主键
            var targetGrain = grainFactory.GetGrain<IYourGrainInterface>(context.Principal?.Identity?.Name);
            await targetGrain.DeactivateAsync();
            
            await Task.CompletedTask;
        },
        // 其他事件处理...
    };
});

方法2:通过AddOpenIdConnect的重载注入服务提供者

使用接收IServiceProvider参数的AddOpenIdConnect重载,提前获取所需服务或者保留服务提供者引用:

.AddOpenIdConnect("oidc", (serviceProvider, options) =>
{
    // 其他OIDC配置项...
    // 提前获取IGrainFactory
    var grainFactory = serviceProvider.GetRequiredService<IGrainFactory>();

    options.Events = new OpenIdConnectEvents
    {
        OnRedirectToIdentityProviderForSignOut = async context =>
        {
            // 直接使用提前获取的grainFactory
            var targetGrain = grainFactory.GetGrain<IYourGrainInterface>(context.Principal?.Identity?.Name);
            await targetGrain.DeactivateAsync();
            
            await Task.CompletedTask;
        }
    };
});

方法3:自定义OpenIdConnectEvents类(适合复杂逻辑)

如果登出事件的业务逻辑比较复杂,建议自定义一个继承自OpenIdConnectEvents的类,通过构造函数注入依赖:

步骤1:实现自定义Events类

public class CustomOidcSignOutEvents : OpenIdConnectEvents
{
    private readonly IGrainFactory _grainFactory;

    // 构造函数注入所需服务
    public CustomOidcSignOutEvents(IGrainFactory grainFactory)
    {
        _grainFactory = grainFactory;
    }

    public override async Task RemoteSignOut(RemoteSignOutContext context)
    {
        // 执行Grain停用逻辑
        var targetGrain = _grainFactory.GetGrain<IYourGrainInterface>(context.Principal?.Identity?.Name);
        await targetGrain.DeactivateAsync();
        
        // 别忘了调用基类方法确保默认流程执行
        await base.RemoteSignOut(context);
    }
}

步骤2:注册并使用自定义Events

在Program.cs中先注册自定义类,再配置OIDC时使用:

// 注册自定义Events类(根据生命周期选择Scoped/Transient)
builder.Services.AddScoped<CustomOidcSignOutEvents>();

builder.Services.AddAuthentication()
    .AddOpenIdConnect("oidc", (serviceProvider, options) =>
    {
        // 其他OIDC配置项...
        // 从服务提供者获取自定义Events实例
        options.Events = serviceProvider.GetRequiredService<CustomOidcSignOutEvents>();
    });

内容的提问来源于stack exchange,提问作者ADringer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 02:16:26