为自定义事件和指标注入应用程序见解

spo*_*ahn 2 dependency-injection azure-application-insights asp.net-core

在具有依赖项注入的ASP.NET Core中,使用自定义事件和指标获取应用程序见解的“正确”方法是什么?有没有办法注入TelemetryClient

我能找到的所有内容都TelemetryClient直接实例化了实例,并且TelemetryClient没有实现接口。

cij*_*mas 6

使用.UseApplicationInsights()AddApplicationInsights()方法配置Application Insights时,TelemetryClient会自动注入到DI中。您可以使用构造函数注入来获取TelemetryClient实例,如下所示。

public class HomeController : Controller
{
    private TelemetryClient telemetry;

    public HomeController(TelemetryClient telemetry)
    {
        this.telemetry = telemetry;
    }

    public IActionResult Index()
    {
        this.telemetry.TrackEvent("HomePageRequested");
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Custom-Configuration#track-custom-traceeventmetric

  • 我想知道它在单元测试中的表现如何? (2认同)
  • 我发现有两种方法可以测试“ telemetryClient”:1.将“ telemetryClient”包装到自定义类中,然后将其注入您的服务中。2.按照以下文章创建伪造的TelemetryChannel:https://medium.com/@jrolstad/unit-testing-and-microsoft-application-insights-6db0929b39e6 (2认同)