gpt4 book ai didi

azure - 如何以及在何处在网络核心 Web 应用程序中设置 TelemetryClient?

转载 作者:行者123 更新时间:2023-12-01 09:21:05 25 4
gpt4 key购买 nike

我希望使用与遥测客户端关联的 TrackTrace 方法。需要创建 TelemetryClient 的实例才能访问此方法。

TelemetryClient 可以在 Controller 的构造函数中初始化,但我想看看是否有更好的方法以及如何实现?

最佳答案

引自Microsoft Docs :

Get an instance of TelemetryClient by using constructor injection, and call the required TrackXXX() method on it. We don't recommend creating new TelemetryClient instances in an ASP.NET Core application.

A singleton instance of TelemetryClient is already registered in theDependencyInjection container, which shares TelemetryConfigurationwith rest of the telemetry. Creating a new TelemetryClient instance isrecommended only if it needs a configuration that's separate from therest of the telemetry.

所以你可以将它注入(inject)到任何你需要的地方,如下所示:

using Microsoft.ApplicationInsights;

public class HomeController : Controller
{
private TelemetryClient telemetry;

// Use constructor injection to get a TelemetryClient instance.
public HomeController(TelemetryClient telemetry)
{
this.telemetry = telemetry;
}

public IActionResult Index()
{
// Call the required TrackXXX method.
this.telemetry.TrackEvent("HomePageRequested");
return View();
}

关于azure - 如何以及在何处在网络核心 Web 应用程序中设置 TelemetryClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46238155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com