首页 > 解决方案 > 仅当客户端在 TelemetryConfiguration 的 using 语句中实例化时,在 Applicationinsightss 中使用 TelemetryClient 才有效

问题描述

我正在使用 ApplicationInsights,定义和发送我自己的自定义事件。

我为此使用了遥测客户端。只有当我实例化并使用我的 telemetryclient 对象时,它才有效,如下所示:

        TelemetryClient telemetryClient;
        using (var telemetryConfiguration = new TelemetryConfiguration("instrumentationKey"))
        {
            telemetryClient = new TelemetryClient(telemetryConfiguration);

            telemetryClient.TrackEvent("CustomEvent1");

            telemetryClient.Flush();
            Thread.Sleep(5000);
        }

问题是,我想在不同的服务中注入 TelemtryClient。然而,在同一位置调用此调用不会在门户中生成任何事件:

            TelemetryClient telemetryClient;
        using (var telemetryConfiguration = new TelemetryConfiguration("instrumentationKey"))
        {
            telemetryClient = new TelemetryClient(telemetryConfiguration);

        }


        telemetryClient.TrackEvent("CustomEvent1");

        telemetryClient.Flush();
        Thread.Sleep(5000);

这是使用 TelemtryClient 的错误方式吗?

标签: eventssdkazure-application-insightstelemetry

解决方案


如果您正在编写 .Net 核心应用程序,您可以在 Startup.cs 的 ConfigureServices 方法中配置 TelemetryClient 的依赖注入。有关完整示例,请参见此处

public void ConfigureServices(IServiceCollection services)
{
        ...
        services.AddApplicationInsightsTelemetry();
        ...
}

然后,如果您正在编写 Mvc 应用程序,例如,您可以将 TelemetryClient 注入到您的控制器中,如下所示:

private readonly TelemetryClient tc;

public MyController(TelemetryClient _tc)
{
    tc = _tc;
} 

public HttpResponseMessage Get(int id)
{
    tc.TrackEvent("CustomEvent1");
    ...
}

确保还正确配置您的 appsettings.json:

"ApplicationInsights": {
"InstrumentationKey": "..." }

希望这会有所帮助,安德烈亚斯


推荐阅读