How and where to setup TelemetryClient within a netcore webApp?

Viewed 1997

I am looking to use the TrackTrace method associated with Telemetry client. An instance of TelemetryClient needs to be created in order to access this method.

A TelemetryClient can be initialised in the constructor of a controller but I was looking to see if there is a better approach and how it would be implemented?

2 Answers

Quote from 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 the DependencyInjection container, which shares TelemetryConfiguration with rest of the telemetry. Creating a new TelemetryClient instance is recommended only if it needs a configuration that's separate from the rest of the telemetry.

So you can just get it injected wherever you need like this:

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();
    }
Related