ApplicationInsights-dotnet: Null Ref Exception when InstrumentationKey is null
We are building some middleware for ASP.NET Core which takes advantage of AI’s handling of the Request-Id
header. While testing the middleware we wanted to enable AI but did not want to report any telemetry. We therefore created:
var appInsightsOptions =
new ApplicationInsightsServiceOptions
{
DeveloperMode = Environment.IsDevelopment()
};
Note that there is no Instrumentation Key. Invoking services.AddApplicationInsightsTelemetry(appInsightsOptions);
with these options succeeds. However, our component under test later makes Web Requests via an HttpClient. These invocations result in a NRE with no useful debugging information.
We worked around this issue by adding an empty-string Instrumentation Key to our AI Options:
var appInsightsOptions =
new ApplicationInsightsServiceOptions
{
DeveloperMode = Environment.IsDevelopment(),
InstrumentationKey = ""
};
Expected:
There are two obvious options:
- Enable HttpClient to work when AI is enabled but an Instrumentation Key is not provided. This is preferred, since AI seems to work [e.g. it reads an incoming request’s
Request-Id
header and propagates it toActivity.Current.Id
] so long as we don’t invoke an HttpClient. - Provide an actionable exception. This would probably be some sort of argument exception when invoking AddApplicationInsightsTelemetry without an Instrumentation Key.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 22 (12 by maintainers)
Commits related to this issue
- Do not reuse TelemetryConfiguration between WebHosts, fix #613 — committed to microsoft/ApplicationInsights-dotnet by deleted user 6 years ago
It seems I have found the root cause for this issue.
It looks like the problem is not
AddApplicationInsights
not being idempoted - it is. The problem is multiple WebHosts running in the same process. I.e. there are several instances of ServiceProvider and each of them has full and valid set of ApplicationInsights services.However since there are a lot of singletons (i.e. static instance, not the DI kind of singleton), their lifetime is not limited to the WebHost.
It’s easy to repro with following tests:
It results in
@mkosieradzki I believe that what’s happen in your case. Could you confirm?
Root cause:
TelemetryConfiguration being a singleton (static instance) is reused by host2. When the host1 is disposed, it causes TelemetyConfiguration instance to be disposed. This results in TelemetryChannel underneath to be disposed and set to null
So when app insights in host2 attempt to track dependency, it leads to the call to null telemetry channel.