I am working with ApplicationInsights, defining and sending my own custom events.
I use the telemetryclient for that. It works only if I instantiate and use my telemetryclient object as following:
TelemetryClient telemetryClient;
using (var telemetryConfiguration = new TelemetryConfiguration("instrumentationKey"))
{
telemetryClient = new TelemetryClient(telemetryConfiguration);
telemetryClient.TrackEvent("CustomEvent1");
telemetryClient.Flush();
Thread.Sleep(5000);
}
The problem is, that I want to inject the telemtryClient in different services. Yet calling this call at the same Position generates no Events in the portal:
TelemetryClient telemetryClient;
using (var telemetryConfiguration = new TelemetryConfiguration("instrumentationKey"))
{
telemetryClient = new TelemetryClient(telemetryConfiguration);
}
telemetryClient.TrackEvent("CustomEvent1");
telemetryClient.Flush();
Thread.Sleep(5000);
Is that the wrong way to use the telemtryClient?
If you are writing a .Net Core Application you can configure dependency Injection of the TelemetryClient in the ConfigureServices method of your Startup.cs. See here for a complete example.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddApplicationInsightsTelemetry();
...
}
Then, if you are writing a Mvc app, for example, you can inject the TelemetryClient in your controllers like this:
private readonly TelemetryClient tc;
public MyController(TelemetryClient _tc)
{
tc = _tc;
}
public HttpResponseMessage Get(int id)
{
tc.TrackEvent("CustomEvent1");
...
}
Make sure to also configure your appsettings.json correctly:
"ApplicationInsights": {
"InstrumentationKey": "..." }
Hope this helps, Andreas