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

授权处理程序无法构造:IMediator依赖注入失败问题排查

问题描述

在Asp.Net Core项目集成Simple Injector时,启动报错:

AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.IAuthorizationHandler Lifetime: Singleton ImplementationType: LM3.NNB.Gateway.WebSite.Infrastructure.Authorisation.IsOwnerHandler': Unable to resolve service for type 'LM3.NNB.Gateway.WebSite.Infrastructure.Mediator.IMediator' while attempting to activate 'LM3.NNB.Gateway.WebSite.Infrastructure.Authorisation.IsOwnerHandler'.)
问题分析
  1. 服务容器不匹配:IsOwnerHandler被注册到ASP.NET Core内置DI容器(MSDI)中,但它依赖的IMediator仅在Simple Injector容器中注册,MSDI无法找到该服务实例。
  2. 生命周期冲突:IsOwnerHandler被注册为Singleton,而IMediator是Scoped生命周期,Singleton依赖Scoped服务会导致捕获依赖问题,ASP.NET Core的DI系统会阻止这种不安全的依赖关系。
解决方案

步骤1:调整IsOwnerHandler的注册容器与生命周期

移除MSDI中对IsOwnerHandler的注册,转而将其注册到Simple Injector,并使用与IMediator一致的Scoped生命周期:

  • 删除授权服务注册代码中的这一行:
    services.AddSingleton<IAuthorizationHandler, IsOwnerHandler>();
    
  • 在InitializeContainer方法中添加Simple Injector注册:
    // 与IMediator生命周期保持一致,避免冲突
    container.Register<IAuthorizationHandler, IsOwnerHandler>(Lifestyle.Scoped);
    

步骤2:让MSDI能获取Simple Injector中的授权处理器

ASP.NET Core授权系统会从内置DI容器获取所有IAuthorizationHandler实例,因此需要将Simple Injector中的实现暴露给MSDI:
修改IntegrateSimpleInjector方法,添加集合注册逻辑:

private void IntegrateSimpleInjector(IServiceCollection services)
{
    services.AddSimpleInjector(container, options =>
    {
        options.AddAspNetCore()
            .AddControllerActivation()
            .AddViewComponentActivation()
            .AddPageModelActivation()
            .AddTagHelperActivation();
        options.AddLogging();
        // 开启跨容器服务解析
        options.AutoCrossWireFrameworkServices = true;
    });

    // 向MSDI注册IAuthorizationHandler集合,从Simple Injector获取所有实现
    services.AddSingleton<IEnumerable<IAuthorizationHandler>>(sp =>
        container.GetAllInstances<IAuthorizationHandler>());
}

验证

启动项目后,授权策略执行时,IsOwnerHandler将由Simple Injector创建并注入正确的IMediator实例,同时生命周期匹配,不会再出现启动报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:10:12