将遥测发送到ConfigureServices内部的ApplicationInsights

时间:2020-11-04 13:03:19

标签: c# asp.net-core .net-core azure-application-insights

我想从ConfigureServices中发送一些遥测信息,例如,如果我缺少配置设置,我想向AI发送事件以进行跟踪。

public class Startup
{
   public void ConfigureServices( IServiceCollection services)
   {
      services.AddApplicationInsightsTelemetry();

      // Is there a way of getting the telemetry client here to send some telemetry?
      // e.g. TelemetryClient.TrackEvent("MyEvent");
   }
}

是否可以通过ConfigureServices来掌握AddApplicationInsightsTelemetry创建的遥测客户端?那时候上下文是否有效?

1 个答案:

答案 0 :(得分:1)

否,在AddApplicationInsightsTelemetry方法完成之前,我们无法掌握ConfigureServicesConfigureServices创建的遥测客户端。

您应按照ConfigureServices方法手动创建遥测客户端,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    var s1 = services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]);

    TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
    configuration.InstrumentationKey = Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
    var telemetryClient = new TelemetryClient(configuration);

    telemetryClient.TrackEvent("xxx");
}