Libraries
    Preparing search index...

    Class ServiceProvider

    An immutable service provider that resolves services from a frozen set of descriptors. Obtain an instance by calling ServiceCollection.buildServiceProvider.

    Supports three service lifetimes:

    • Singleton — one instance per provider, cached after first resolution.
    • Scoped — one instance per ServiceScope, created via createScope.
    • Transient — a new instance on every call to get.
    const provider = services.buildServiceProvider();

    // Typed via the schema — no explicit generic needed
    const config = provider.get(IConfig);
    config.port; // number

    // Optional resolution (returns undefined if not registered)
    const maybeMail = provider.getOptional(IMailer);
    // Per-request scope (e.g. in an HTTP handler)
    using scope = provider.createScope();
    const db = scope.serviceProvider.get(IDbContext);
    // db is disposed when scope exits
    const handlerSchema = func()
    .addParameter(ILogger)
    .addParameter(IDbContext)
    .hasReturnType(string());

    const result = provider.invoke(handlerSchema, (logger, db) => {
    logger.info('Handling request');
    return db.query('SELECT 1');
    });

    Implements

    Index

    Methods

    • Creates a new ServiceScope. Scoped services resolved from the scope's serviceProvider are cached per-scope and disposed when the scope is disposed.

      The returned scope implements both Symbol.dispose and Symbol.asyncDispose, so it works with the using keyword:

      Returns ServiceScope

      A new ServiceScope.

      // Sync disposal
      using scope = provider.createScope();
      const db = scope.serviceProvider.get(IDbContext);

      // Async disposal
      await using scope = provider.createScope();
      const db = scope.serviceProvider.get(IDbContext);
    • Resolves a service by its schema key.

      • Singleton: returns the cached instance, or creates and caches it.
      • Scoped: throws if called from the root provider when validateScopes is true (default). Use createScope to obtain a scoped provider.
      • Transient: creates a new instance on every call.

      Type Parameters

      • TSchema extends SchemaBuilder<any, any, any, any, any>

      Parameters

      • schema: TSchema

        The schema instance used as the service identifier. Must be the same reference used during registration.

      Returns InferType<TSchema>

      The resolved service, typed as InferType<typeof schema>.

      If the schema is not registered.

      If a scoped service is resolved from the root provider with validateScopes enabled.

      If a circular dependency is detected.

      const logger = provider.get(ILogger);
      logger.info('Hello'); // fully typed
    • Resolves a service by its schema key, or returns undefined if the schema is not registered.

      Unlike get, this method does not throw for unregistered schemas. All other behaviour (lifetime, scope validation, circular dependency detection) is the same.

      Type Parameters

      • TSchema extends SchemaBuilder<any, any, any, any, any>

      Parameters

      • schema: TSchema

        The schema instance used as the service identifier.

      Returns InferType<TSchema> | undefined

      The resolved service or undefined.

      const mailer = provider.getOptional(IMailer);
      if (mailer) {
      mailer.send('test@example.com', 'Hello');
      }
    • Resolves the dependencies described by a FunctionSchemaBuilder and calls implementation with the resolved values.

      Each parameter schema in funcSchema.introspect().parameters is resolved from this provider. The implementation receives the resolved values in the same order as the parameter schemas.

      Type Parameters

      • TFuncSchema extends FunctionSchemaBuilder<any, any, any, any, any, any, undefined, any>

      Parameters

      • funcSchema: TFuncSchema

        A FunctionSchemaBuilder whose parameters describe the services to inject.

      • implementation: InferType<TFuncSchema>

        A function whose parameters match the funcSchema parameter types and whose return type matches the funcSchema return type.

      Returns ReturnType<InferType<TFuncSchema>>

      The return value of implementation.

      const handler = func()
      .addParameter(ILogger)
      .addParameter(IConfig)
      .hasReturnType(string());

      const result = provider.invoke(handler, (logger, config) => {
      logger.info(`Running on port ${config.port}`);
      return 'ok';
      });
      // result: string
      • FunctionSchemaBuilder.addParameter
      • FunctionSchemaBuilder.hasReturnType