Support hosted services in WebAssemblyHost #63814
Draft
+230
−1
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.
Fixes #33537
This PR adds support for hosted services (
IHostedService
) inWebAssemblyHost
, enabling automatic startup and shutdown of background services in Blazor WebAssembly applications.Problem
Applications using
WebAssemblyHost
(e.g. Blazor WebAssembly clients) did not support hosted services out of the box. Services registered withAddHostedService
were ignored when usingWebAssemblyHostBuilder
, unlike in applications built withWebApplicationBuilder
orHostApplicationBuilder
. This prevented libraries like OpenTelemetry from working properly in Blazor WebAssembly apps, as they rely on hosted services for initialization.Solution
The implementation adds hosted service lifecycle management to
WebAssemblyHost
:IHostedService
implementations from the DI containerRunAsyncCore()
after component state restorationDisposeAsync()
with proper error handlingUsage
Developers can now register hosted services in Blazor WebAssembly apps:
Implementation Details
Microsoft.Extensions.Hosting.Abstractions
reference to enableIHostedService
supportTesting
Added comprehensive test coverage:
All existing WebAssemblyHost functionality remains unchanged and all tests pass.
Original prompt
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.