Home > Net >  How do you implement DisposeAsync on an ApiController?
How do you implement DisposeAsync on an ApiController?

Time:04-28

I have the following code to put a json api over a grpc service. A ValueTask is returned when releasing the service activator handle. Code linting suggested that this code should be awaited, but when I refactored to use the DisposeAsync pattern MapControllers throws an Exception ("DisposeAsync does not have an attribute route").

[ApiController]
public class GatewayController : Controller, IAsyncDisposable
{
    private readonly GrpcService _grpcService;
    private readonly IGrpcServiceActivator<GrpcService> _serviceActivator;
    private readonly GrpcActivatorHandle<GrpcService> _activatorHandle;

    public GatewayController(
        IGrpcServiceActivator<GrpcService> serviceActivator, 
        IServiceProvider serviceProvider)
    {
        _serviceActivator = serviceActivator;
        _activatorHandle = serviceActivator.Create(serviceProvider);
        _grpcService = _activatorHandle.Instance;
    }

    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore();
        Dispose(false);
        GC.SuppressFinalize(this);
    }

    protected virtual async ValueTask DisposeAsyncCore()
    {
        // returns a ValueTask that is warned as "should be awaited"
        await _serviceActivator.ReleaseAsync(_activatorHandle);
    }
}

How do you implement DisposeAsync on an ApiController?

CodePudding user response:

Use NonActionAttribute:

Indicates that a controller method is not an action method.

[NonAction]
public async ValueTask DisposeAsync()
{
   ...
}

Or explicit interface implementation:

async ValueTask IAsyncDisposable.DisposeAsync()
{
   ...
}
  • Related