Fix TelemetryClient.Flush/FlushAsync NullReferenceException in DI scenarios #3125
Fix TelemetryClient.Flush/FlushAsync NullReferenceException in DI scenarios #3125rajkumar-rangaraj merged 4 commits intomainfrom
Conversation
There was a problem hiding this comment.
Pull request overview
This pull request fixes a NullReferenceException in TelemetryClient.Flush() and FlushAsync() methods when called in dependency injection (DI) scenarios. The issue occurred because in DI scenarios, TelemetryClient is constructed with isFromDependencyInjection: true, which intentionally skips building the OpenTelemetry SDK (since it's managed by the DI container via AddOpenTelemetry()). However, both flush methods unconditionally accessed this.sdk.TracerProvider, causing a NullReferenceException when sdk was null.
Changes:
- Added
IServiceProviderfield toTelemetryClientand a new internal constructor that accepts it - Updated DI registration to pass the
IServiceProvidertoTelemetryClient - Modified
Flush()andFlushAsync()to check if SDK is available first, then fall back to resolving providers from DI container
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs | Added serviceProvider field, new constructor accepting IServiceProvider, and updated Flush()/FlushAsync() to resolve OTel providers from DI when sdk is null |
| NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs | Updated TelemetryClient factory registration to pass IServiceProvider to the new constructor |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
harsimar
left a comment
There was a problem hiding this comment.
How was this tested? Consider adding some automated testing
We don't have an automated infra built yet. It's outside the scope of the PR. We might need to consider building one. |
|
I'm running in this issue; what is the expected release date of this fix? |
Within 2 weeks. |
Fix Issue #3115 .
Changes
TelemetryClient.Flush()andFlushAsync()throwSystem.NullReferenceExceptionwhen called from DI scenarios becausethis.sdkis null.In DI scenarios,
TelemetryClientis constructed withisFromDependencyInjection: true, which intentionally skips callingTelemetryConfiguration.Build()— the OTel SDK is owned byAddOpenTelemetry()in the DI container, not byTelemetryConfiguration. However, bothFlush()andFlushAsync()unconditionally accessthis.sdk.TracerProvider, causing:IServiceProviderfield and a new internal constructor that accepts itTelemetryClientfactory inAddTelemetryConfigAndClientto pass theIServiceProviderFlush()andFlushAsync()now check: ifthis.sdkis available (non-DI), flush via the SDK; otherwise ifthis.serviceProvideris available (DI), resolveTracerProvider/MeterProvider/LoggerProviderfrom the DI container and flush those