Function Injectable

  • Creates an Injectable factory function designed for services without dependencies. This is useful for simple services or values that don't depend on other parts of the system.

    Type Parameters

    • Token extends TokenType
    • Service

    Parameters

    • token: Token

      A unique Token identifying the Service within the container. This token is used to retrieve the instance from the container.

    • fn: (() => Service)

      A zero-argument function that initializes and returns the Service instance. This can be any class instance, primitive, or complex value meant to be managed within the DI container.

    Returns InjectableFunction<any, [], Token, Service>

    const container = Container.provides(Injectable("MyService", () => new MyService()));

    const myService = container.get("MyService");
  • Creates an Injectable factory function that requires dependencies.

    The dependencies are specified as tokens, and the factory function will receive these dependencies as arguments in the order they are listed.

    Note: Dependencies must be specified as constant literals to allow TypeScript to ensure type safety.

    Note: Starting with TypeScript version 5, the as const assertion in the example below is not needed due to the introduction of const type parameters feature.

    Type Parameters

    • Token extends TokenType
    • const Tokens extends readonly TokenType[]
    • Params extends readonly any[]
    • Service

    Parameters

    • token: Token

      A unique Token identifying the Service within the container.

    • dependencies: Tokens

      A readonly array of Tokens representing the dependencies required by the factory function. These will be resolved by the container and provided as arguments to the factory function.

    • fn: ((...args: Tokens["length"] extends Params["length"]
          ? Params
          : void[]) => Service)

      A factory function whose parameters match the dependencies. This function should initialize and return an instance of the Service. The types and number of its parameters must exactly match the dependencies.

    Returns Tokens["length"] extends Params["length"]
        ? InjectableFunction<ServicesFromTokenizedParams<Tokens, Params>, Tokens, Token, Service>
        : never

    const dependencyB = 'DependencyB';
    const container = Container
    .providesValue("DependencyA", new A())
    .providesValue("DependencyB", new B())
    .provides(Injectable(
    "MyService",
    ["DependencyA", dependencyB] as const, // "as const" can be omitted in TypeScript 5 and later
    (a: A, b: B) => new MyService(a, b),
    )
    )

    const myService = container.get("MyService");