-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor Components
Milestone
Description
Background and Motivation
When we implemented IAsyncDisposable
in components we should probably have also added support for this on OwningComponentBase
. Previously, developers faced two main problems:
When the injected service implements IAsyncDisposable
, an exception is thrown: "System.InvalidOperationException: 'MyService' type only implements IAsyncDisposable. Use DisposeAsync to dispose the container."
Proposed API
namespace Microsoft.AspNetCore.Components
{
public abstract class OwningComponentBase : ComponentBase, IDisposable, IAsyncDisposable
{
// ...existing members...
+ protected virtual ValueTask DisposeAsyncCore();
}
}
Usage Examples
// Component with async disposable service
public class ChatComponent : OwningComponentBase<IChatService>
{
// Service that implements IAsyncDisposable (e.g., has SignalR HubConnection)
private IChatService ChatService => Service;
protected override async ValueTask DisposeAsyncCore()
{
// Custom async cleanup if needed
await base.DisposeAsyncCore();
}
}
// Component that implements IAsyncDisposable
public class MyAsyncComponent : OwningComponentBase, IAsyncDisposable
{
// Component's own async resources
private SomeAsyncResource? _resource;
protected override async ValueTask DisposeAsyncCore()
{
if (_resource != null)
{
await _resource.DisposeAsync();
}
await base.DisposeAsyncCore();
}
}
Alternative Designs
The main alternative considered was to not implement this feature due to potential breaking changes. Adding IAsyncDisposable
implementation with a protected virtual DisposeAsyncCore()
method could clash with existing IAsyncDisposable
implementations in subclasses, requiring developers to change their implementations to override the new base-class method.
Risks
- Potential breaking changes: Existing components that inherit from
OwningComponentBase
and implementIAsyncDisposable
may need to update their implementation to override the newDisposeAsyncCore()
method instead of implementingIAsyncDisposable
directly.
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor Components