Using Static Instance of TelemetryClient with Application Insights

William picture William · Jan 10, 2016 · Viewed 14.6k times · Source

I have an ASP.NET MVC Website and I am implementing Application Insights. Right now, I log a Trace Event as follows:

private static TelemetryClient _APM;
private static TelemetryClient APM
{
    get
    {
        if (_APM == null) { _APM = new TelemetryClient(); }
        return _APM;
    }
}

public static void Trace(string Message)
{
    APM.TrackTrace(Message);
}

As you can see, this would maintain a single static instance of the TelemetryClient for all traces. Is this how we are supposed to use the client? Or are we supposed to create a new instance of TelemetryClient for each Log?

Answer

darth_phoenixx picture darth_phoenixx · Jan 10, 2016

According to the docs you should:

... use an instance of TelemetryClient for each module of your app. For instance, you may have one TelemetryClient in your web service to report incoming http requests, and another in a middleware class to report business logic events.

It is probably expensive to create a new telemetry client for every log, so depending on the structure of your application you are probably right to use the singleton pattern you have described in your post.