Minimal dependency injection container interface.

Defines the core contract that any DI container must implement. Implementation-agnostic - works with any DI library.

// Resolve services
const logger = container.resolve<Logger>('logger');
const userService = container.resolve<UserService>('userService');

// Create scopes for request-scoped services
const scope = container.createScope();
const requestContext = scope.resolve<RequestContext>('requestContext');
await scope.dispose();
interface Container {
    resolve<T>(token: string | symbol): T;
    createScope(): Container;
    dispose(): Promise<void>;
}

Methods

  • Resolves a service from the container.

    Type Parameters

    • T

      The type of service to resolve

    Parameters

    • token: string | symbol

      The service identifier (string or symbol)

    Returns T

    The resolved service instance

    Error if the service is not registered

    const logger = container.resolve<Logger>('logger');
    const cache = container.resolve<Cache>(Symbol.for('cache'));
  • Creates a new scope for scoped services.

    Scoped services will have the same instance within a scope, but different instances across different scopes. Useful for request-scoped dependencies in web applications.

    Returns Container

    A new container scope

    const scope = container.createScope();
    const service1 = scope.resolve<ScopedService>('scopedService');
    const service2 = scope.resolve<ScopedService>('scopedService');
    // service1 === service2 (same scope)

    const scope2 = container.createScope();
    const service3 = scope2.resolve<ScopedService>('scopedService');
    // service3 !== service1 (different scope)
  • Disposes the container and all disposable services.

    Services implementing dispose() or Symbol.asyncDispose will have their disposal methods called.

    Returns Promise<void>

    Promise that resolves when all services are disposed

    const scope = container.createScope();
    // Use scope...
    await scope.dispose(); // Clean up resources