4

I am trying to set the InstrumentationKey of AppInsights TTelemetry from appsettings.json. My code looks like this

Program.cs

 WebHost.CreateDefaultBuilder(args)
            .UseApplicationInsights()
            .UseStartup<Startup>()
               .ConfigureAppConfiguration((hostingContext, config) =>
               {
                   config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
               });

Startup.cs, ConfigureServices()

        services.AddApplicationInsightsTelemetry(Configuration);

appsettings.json

  "ApplicationInsights": {
    "InstrumentationKey": "[my key]"
  },

However, when I run _serviceProvider.GetService(), or recieved the TelemetryClient via dependecy injection in the controller, the telemetry.Context.InstrumentationKey is empty.

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
Anish
  • 3,045
  • 3
  • 27
  • 29

1 Answers1

2

This is by design.

TelemetryClient.InstrumentationKey or TelemetryClient.Context.InstrumentationKey should be empty unless you explicitly set it there as an override of what is in configuration.

As mentioned above, explicitly set it like: TelemetryClient client = new TelemetryClient() { InstrumentationKey= "your_ikey" };, then you can use .Context.InstrumentationKey to get the key.

And you can find the details on this issue.

Hope it helps.

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
  • 6
    That doesn't many sense. TelemetryClient instance is being created by dependency injection. I'm not creating an instance of it. It is supposed to pick the key from Configuration. – Anish Feb 26 '19 at 13:52
  • If you have any concern, you can comment on that [thread](https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/141) I mentioned, or submit a new issue on [application insights GitHub](https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues). – Ivan Glasenberg Feb 27 '19 at 07:13
  • 3
    Agreed that this makes no sense. Configured app insights with an instrumentation key and using the provider.GetService() has no key set. How does it get set when injecting into controllers? new TelemetryClient() is obsoleted now so this seems wrong... – MPavlak Feb 18 '20 at 05:19
  • 3
    "This is by design" :D.. well this is a bad design. – nbilal Mar 14 '20 at 10:52