vlocode-project - v1.40.0-beta-4
    Preparing search index...

    Class Container

    The DI container can be used to register and resolve dependencies automatically. It supports constructor injection and property injection of dependencies. There are two built-in lifecycle policies: LifecyclePolicy.singleton and LifecyclePolicy.transient.

    The DI framework uses two decorators to mark classes and properties as injectable:

    • injectable to mark a class as injectable
    • inject to mark a property or constructor parameter as injectable

    When creating a class through the container, constructor parameters will automatically be resolved by type. When creating a class outside of the container, constructor parameters will not be resolved.

    Injectable properties are resolved lazily when they are first accessed and are cached for subsequent access on a unique symbol on the instance for which they are resolved. Resolution of injectable properties uses the container that created the instance. If the instance was created outside of a container, the root container is used to try and resolve the dependency.

    When the container cannot resolve a dependency it will return undefined for properties and constructor parameters marked with inject decorator.

    The DI framework requires the following tsconfig settings to be enabled:

    • emitDecoratorMetadata: true (required to emit type metadata for decorated classes and properties)
    • experimentalDecorators: true (required to use decorators at all)
    • useDefineForClassFields: false (required in order to use inject)

    @example:

    @injectable()
    class Bar {
    constructor(private foo: Foo) {
    }

    public helloFooBar() {
    this.foo.helloBar();
    }

    public hello() {
    console.log('Hello!');
    }
    }

    @injectable()
    class Foo {
    constructor(public bar: Bar) {
    }

    public helloBar() {
    this.bar.hello();
    }
    }

    container.new(Foo).helloBar(); // prints 'Hello!'
    container.new(Foo).bar.helloFooBar(); // prints 'Hello!'
    Index

    Constructors

    Properties

    containerGuid: string = ...
    containerPath: string
    factories: Map<string, { lifecycle?: LifecyclePolicy; new: TypeFactory }> = ...
    instances: Map<string, any> = ...
    logger: Logger = ...
    parent?: Container
    providers: Map<string, (receiver: any) => any> = ...
    resolveStack: string[] = ...
    serviceDependencies: Map<string, string[]> = ...
    servicesProvided: symbol = ...
    serviceTypes: Map<string, { ctor: TypeConstructor; options?: ServiceOptions }[]> = ...
    useInstanceProxies: boolean = false

    Wrap all instance created by this container in Proxies. When set to true each service instance created by this container is wrapped in a Proxy. Proxied service instances behave the same way as non-proxied service instances but each call will be routed through the proxy which can impact performance.

    For now the recommended setting is false unless you need to dynamically swap service instances without recreated the dependencies that use them.

    For circular references proxies will always be used even when useInstanceProxies is set to false

    root: Container

    Global root container; by default all services are contained in there

    Accessors

    • get isRoot(): boolean

      Returns true if this container is the root container of the application. The root container is the container that is created by default and contains all services by default.

      Returns boolean

    Methods

    • Create a new container that inherits all configuration form the parent but on top of that can register or overwrite dependencies; by default dependency resolution is first attempted using the providers, factories and registered service instance in the new container; if that fails it resolution is delegated to the parent until the root container which will throw an exception in case it cannot resolve the requested module.

      Parameters

      • Optionaloptions: { isolated?: boolean }

      Returns Container

    • Internal function to get the property descriptor for an injectable property; used by the inject decorator.

      Parameters

      • propertyKey: string | symbol

        Key of the property to get the descriptor for

      Returns {
          "[InjectedPropertyKey]": string | symbol;
          configurable: boolean;
          enumerable: boolean;
          get(): any;
          set(): never;
      }

      Defined property descriptor

    • Create a new instance of a type resolving constructor parameters as dependencies using the container. The returned class is not added in the container even when the lifecycle policy is singleton.

      Type Parameters

      Parameters

      • ctor: T

        Constructor/Type to instantiate

      • ...params: PartialArray<ConstructorParameters<T>>

        Constructor params provided

      Returns InstanceType<T>

      New instance of an object who's dependencies are resolved by the container

    • Create a new instance of the given type, with construction wrapped in a deferred initializer.

      The type and any provided partial constructor arguments are forwarded to the container's createInstance method. The actual construction is wrapped with lazy(...) so the creation logic is executed by the lazy initializer; this method invokes that initializer and returns the created instance.

      Type Parameters

      Parameters

      • ctor: T

        The constructor (class or function) to instantiate.

      • ...params: PartialArray<ConstructorParameters<T>>

        A partial array of constructor arguments that will be forwarded to createInstance.

      Returns InstanceType<T>

      The constructed instance of the specified constructor type.

    • Type Parameters

      • T extends object
      • I extends object = T

      Parameters

      • service: ObjectType<T>
      • provider: (receiver: any) => undefined | I | Promise<I>

      Returns void

    • Register a service proxy that can be manually set with a concrete instance later on. Any instance that request a service of type T will receive the proxy instance.

      The proxy is not registered as a factory type.

      The proxy instance can be set using the setInstance method on the ProxyTarget returned by this method.

      Type Parameters

      • T extends object

      Parameters

      • type: { name: string; prototype: T }

        Service type to register

      Returns ProxyTarget<T>

      ProxyTarget instance that can be used to set the concrete instance

    • Drops an active singleton service instance from the container causing subsequent resolutions to create a new instances instead of reusing the existing one.

      Parameters

      • instance: unknown

        the instance to remove

      Returns void

    • Resolve injectable parameters for a service using this container.

      Type Parameters

      • T extends new (...args: any[]) => any

      Parameters

      • ctor: T

        Constructor function

      • args: any[] = []

        arguments

      • OptionalinstanceGuid: string

        instance guid

      Returns any[]

    • Resolve injectable properties for a service using this container.

      Type Parameters

      • T extends object

      Parameters

      • instance: T

        Instance object

      Returns T

      instance

    • Resolve a single property on an instance

      Parameters

      • instance: object

        The instance containing the property

      • property: string | symbol

        The name of the property to resolve

      • Optionaloptions: { trackAsDependency?: boolean }

      Returns any

      The resolved property value

    • Register a new dependency between two services

      Parameters

      • serviceGuid: string

        the instance guid of the object that owns the dependency

      • dependsOn: object

        instance of the dependency

      Returns void

    • Use the specified instance to provided the specified service types. If an existing service is already registered for a type, it will be replaced with the new instance.

      Parameters

      • instance: object

        the service instance

      • Optionaltypes: ObjectType<object> | ObjectType<object>[]

        the service types to provide

      Returns void