首页 > 解决方案 > 使用依赖注入在派生的 ActionFilterAttribute 中获取 RequestTelemetry(或 ITelemetry)

问题描述

如何使用依赖注入ITelemety在 ASP.NET Core 自定义中获取对象的对象?ActionFilterAttribute

平台 - .Net Core

需要什么:ITelemetry 对象

示例代码供参考

  public class CustomActionFilterAttribute : ActionFilterAttribute
  {
    private readonly ITelemetry telemetry;

    public CustomActionFilterAttribute(ITelemetry telemetry)
    {
        this.telemetry= telemetry;
    }
   }

我需要解析ITelemetry对象以在请求上下文中添加一些全局属性,以便可以将这些属性记录在请求日志中。ITelemetry使用上面的示例代码,当DI 未解析对象时会引发异常。

CustomActionFilterAttribute启动时注入如下所示。

services.AddMvc(options =>
 {
       options.Filters.Add<CustomActionFilterAttribute>();
 });

标签: azure-application-insights

解决方案


推荐阅读