Fix NullReferenceException in WorkflowHost with .NET 8+ dependency injection #1404
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Describe the change
Fixes
NullReferenceExceptionoccurring when WorkflowHost starts on .NET 8+ with newer Microsoft.Extensions.DependencyInjection versions (8.0+, 9.0+, 10.0+).Describe your implementation or design
Two separate issues were causing NullReferenceException:
DI Registration Issue: Using
GetService<T>()instead ofGetRequiredService<T>()when registering ILifeCycleEventPublisher as an IBackgroundTask meant that if the service failed to resolve,nullwould be added to theIEnumerable<IBackgroundTask>collection, causing a NullReferenceException when iterating.Activity Tracing Issue: When OpenTelemetry tracing is not enabled,
WorkflowActivity.StartHost()returnsnull. The exception handler inStartAsyncwas callingactivity.AddException(ex)without checking for null, causing a NullReferenceException.Changes:
sp.GetService<ILifeCycleEventPublisher>()tosp.GetRequiredService<ILifeCycleEventPublisher>()for fail-fast behavior with clear error messagesStartAsync()andStopAsync()as defensive programmingactivity.AddException(ex)toactivity?.AddException(ex)to handle null activity when OpenTelemetry tracing is disabledTests
Verified with .NET 10 runtime and Microsoft.Extensions.DependencyInjection 10.0.0:
Breaking change
No. If ILifeCycleEventPublisher cannot be resolved (which shouldn't happen in valid configurations), the code now throws a clear exception during service registration instead of a cryptic runtime error—this is an improvement in error reporting.
Additional context
The fail-fast approach provides better diagnostics for misconfigured DI containers while the null checks provide defense-in-depth. The activity null-check ensures compatibility whether OpenTelemetry tracing is enabled or not.
Original prompt
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.