Skip to content

Documentation should recommend CreateAsyncScope instead of CreateScope #12560

@sachinwfs

Description

@sachinwfs

Type of issue

Outdated article

Description

The documentation tells developers to call CreateScope. If one of the services retrieved implements IAsyncDisposable and not IDisposable, an exception will be thrown by the scope on disposal. The documentation should use CreateAsyncScope instead.

Steps to reproduce:

  1. Follow tutorial as written.
  2. Declare DefaultScopedProcessingService as IAsyncDisposable
public sealed class DefaultScopedProcessingService(ILogger<DefaultScopedProcessingService> logger) : IScopedProcessingService, IAsyncDisposable
{
    // existing code goes here

    ValueTask IAsyncDisposable.DisposeAsync()
    {
        logger.LogInformation(
            "{ServiceName} disposing, instance ID: {Id}",
            nameof(DefaultScopedProcessingService),
            _instanceId);

        return ValueTask.CompletedTask;
    }
}
  1. Run dotnet run and see output:
fail: Microsoft.Extensions.Hosting.Internal.Host[9]
      BackgroundService failed
      System.InvalidOperationException: 'App.ScopedService.DefaultScopedProcessingService' type only implements IAsyncDisposable. Use DisposeAsync to dispose the container.
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.Dispose()
         at App.ScopedService.ScopedBackgroundService.ExecuteAsync(CancellationToken stoppingToken) in C:\path\to\project\App.ScopedService\Worker.cs:line 24
         at App.ScopedService.ScopedBackgroundService.ExecuteAsync(CancellationToken stoppingToken)
         at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)

Suggested fix:

ScopedBackgroundService should use CreateAsyncScope instead of CreateScope:

// bad:
using IServiceScope scope = serviceScopeFactory.CreateScope();
// good:
await using AsyncServiceScope scope = serviceScopeFactory.CreateAsyncScope();

Page URL

https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.iservicescopefactory.createscope?view=net-10.0-pp#microsoft-extensions-dependencyinjection-iservicescopefactory-createscope

Content source URL

https://github.com/dotnet/dotnet-api-docs/blob/main/xml/Microsoft.Extensions.DependencyInjection/IServiceScopeFactory.xml

Document Version Independent Id

4a460e1c-ded4-94a1-889f-63b4abfcdc0a

Platform Id

da11c361-64ee-74eb-a219-103594760041

Article author

@dotnet-bot

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-area-labelAn area label is needed to ensure this gets routed to the appropriate area owners

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions