Libraries
    Preparing search index...

    Class ServiceScope

    A scoped service container that caches Scoped services for the duration of its lifetime. Obtain instances via ServiceProvider.createScope.

    The scope tracks all created scoped services that implement Disposable or AsyncDisposable and disposes them in reverse creation order (LIFO) when the scope is disposed. This matches .NET's scope disposal semantics.

    Supports the using keyword via Symbol.dispose and Symbol.asyncDispose:

    using scope = provider.createScope();
    const db = scope.serviceProvider.get(IDbContext);
    // db is automatically disposed when the block exits
    await using scope = provider.createScope();
    const db = scope.serviceProvider.get(IDbContext);
    // db is asynchronously disposed when the block exits
    const scope = provider.createScope();
    try {
    const db = scope.serviceProvider.get(IDbContext);
    // use db...
    } finally {
    await scope.asyncDispose();
    }

    Implements

    • Disposable
    • AsyncDisposable
    Index

    Properties

    serviceProvider: ScopedServiceProvider

    A child IServiceProvider that resolves services within this scope.

    • Singleton services are resolved from the root provider's cache.
    • Scoped services are resolved from this scope's cache (created on first access, reused within the scope).
    • Transient services create a new instance on every call.
    const scope = provider.createScope();
    const db = scope.serviceProvider.get(IDbContext); // scoped
    const logger = scope.serviceProvider.get(ILogger); // singleton from root

    Methods

    • Implements the asynchronous AsyncDisposable protocol. Delegates to asyncDispose.

      Returns Promise<void>

      await using scope = provider.createScope();
      
    • Implements the synchronous Disposable protocol. Delegates to dispose.

      Returns void

      using scope = provider.createScope();
      
    • Asynchronously disposes all scoped services that implement Symbol.asyncDispose or Symbol.dispose, in reverse creation order (LIFO).

      For each service:

      • If it implements Symbol.asyncDispose, that method is awaited.
      • Otherwise, if it implements Symbol.dispose, that method is called synchronously.

      Returns Promise<void>

      Re-throws the first error encountered during disposal, but still attempts to dispose remaining services.

    • Synchronously disposes all scoped services that implement Symbol.dispose, in reverse creation order (LIFO).

      Services that only implement Symbol.asyncDispose are skipped during synchronous disposal. Use asyncDispose to properly dispose all services including async ones.

      Returns void

      Re-throws the first error encountered during disposal, but still attempts to dispose remaining services.