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

如何在Program.cs中为LogAction过滤器注入IServiceProvider?

解决方案

方案1:使用类型注册全局过滤器(推荐)

你不需要手动传入IServiceProvider,ASP.NET Core框架会自动处理过滤器的依赖注入,步骤如下:

  1. 将LogAction注册到依赖注入容器:
    在Program.cs中添加:

    builder.Services.AddScoped<LogAction>();
    

    (生命周期可根据需求选择AddScoped/AddTransient/AddSingleton)

  2. 修改过滤器注册方式:
    不要直接new实例,而是通过类型添加:

    builder.Services.AddControllers(config =>
    {
        config.Filters.Add<LogAction>();
        // 也可使用AddService方法,效果一致
        // config.Filters.AddService<LogAction>();
    });
    

方案2:优化依赖注入,直接注入所需服务(更符合DI原则)

你当前通过IServiceProvider获取ISecurity属于ServiceLocator模式,建议直接在构造函数中注入ISecurity,简化代码:

  1. 修改LogAction类:

    public class LogAction: ActionFilterAttribute
    {
      private readonly ISecurity _security;
      
      public LogAction(ISecurity security)
      {
        _security = security;
      }
    
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
        // 直接使用_security即可
        // rest of the code 
      }
    }
    
  2. 注册ISecurity和LogAction:
    确保ISecurity的实现类已注册到DI:

    builder.Services.AddScoped<ISecurity, SecurityImplementation>();
    builder.Services.AddScoped<LogAction>();
    
  3. 注册全局过滤器:
    同方案1的方式:

    builder.Services.AddControllers(config =>
    {
        config.Filters.Add<LogAction>();
    });
    

原方式失效原因

在Program.cs的AddControllers配置阶段,DI容器尚未完全构建完成,无法直接获取IServiceProvider实例传入过滤器构造函数。通过类型注册的方式,框架会在后续请求处理时从已构建的DI容器中自动解析过滤器的依赖项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:25:04