Skip to content

API proposal OwningComponentBase IAsyncDisposable implementation #62714

@javiercn

Description

@javiercn

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

  1. Potential breaking changes: Existing components that inherit from OwningComponentBase and implement IAsyncDisposable may need to update their implementation to override the new DisposeAsyncCore() method instead of implementing IAsyncDisposable directly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-blazorIncludes: Blazor, Razor Components

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions