AdonisJS API
    Preparing search index...

    Class Container<KnownBindings>

    The container class exposes the API to register bindings, values and resolve them.

    Known bindings types can be defined at the time of the constructing the container.

    new Container<{ 'route': Route, encryption: Encryption }>()
    

    You can resolve bindings and construct classes as follows

    await container.make(BINDING_NAME)
    await container.make(CLASS_CONSTRUCTOR)

    Type Parameters

    • KnownBindings extends Record<any, any>
    Index
    • Initialize the container with optional configuration

      Type Parameters

      • KnownBindings extends Record<any, any>

      Parameters

      • Optionaloptions: ContainerOptions

        Optional container configuration including event emitter

      Returns Container<KnownBindings>

      const container = new Container()
      
      const container = new Container<{
      route: Route
      encryption: Encryption
      }>({ emitter: eventEmitter })
    • Define an emitter instance to use for container events

      Parameters

      • emitter: { emit(event: string | symbol, ...values: any[]): any }

        Event emitter instance that implements emit method

      Returns Container<KnownBindings>

      const container = new Container()
      container.useEmitter(eventEmitter)
    • Create a container resolver to resolve bindings, or make classes.

      const resolver = container.createResolver()
      await resolver.make(CLASS_CONSTRUCTOR)

      Bind values with the resolver. Resolver values are isolated from the container.

      resolver.bindValue(HttpContext, new HttpContext())
      await resolver.make(UsersController)

      Returns ContainerResolver<KnownBindings>

      A new container resolver instance

    • Find if the container has a binding registered using the "bind", the "singleton", the "bindValue", or the "if" methods.

      A registered binding is not always resolvable. When a binding key only has conditional bindings registered for it, this method returns true, but resolving it still fails if none of the conditions match.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      • binding: Binding

        The binding key to check for

      Returns boolean

      container.hasBinding('route')
      container.hasBinding(Route)
    • Find if the container has a binding registered using the "bind", the "singleton", the "bindValue", or the "if" methods.

      A registered binding is not always resolvable. When a binding key only has conditional bindings registered for it, this method returns true, but resolving it still fails if none of the conditions match.

      Parameters

      • binding: BindingKey

        The binding key to check for

      Returns boolean

      container.hasBinding('route')
      container.hasBinding(Route)
    • Find if the container has all the bindings registered using the "bind", the "singleton", the "bindValue", or the "if" methods.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      • bindings: Binding[]

        Array of binding keys to check for

      Returns boolean

      container.hasAllBindings(['route', 'encryption'])
      container.hasAllBindings([Route, Encryption])
    • Find if the container has all the bindings registered using the "bind", the "singleton", the "bindValue", or the "if" methods.

      Parameters

      Returns boolean

      container.hasAllBindings(['route', 'encryption'])
      container.hasAllBindings([Route, Encryption])
    • Resolves the binding or constructor a class instance as follows.

      • Resolve the binding from the values (if registered)
      • Resolve the binding from the bindings (if registered)
      • If binding is a class, then create a instance of it. The constructor dependencies are further resolved as well.
      • All other values are returned as it is.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      • binding: Binding

        The binding key or class constructor to resolve

      • OptionalruntimeValues: any[]

        Optional array of runtime values for constructor dependencies

      • OptionalcreateError: ErrorCreator

        Optional custom error creator function

      Returns Promise<
          Binding extends string | symbol ? KnownBindings[Binding] : Make<Binding>,
      >

      await container.make('route')
      await container.make(Database)
      await container.make(UsersController, [request, response])
    • Resolves the binding or constructor a class instance as follows.

      • Resolve the binding from the values (if registered)
      • Resolve the binding from the bindings (if registered)
      • If binding is a class, then create a instance of it. The constructor dependencies are further resolved as well.
      • All other values are returned as it is.

      Type Parameters

      • Binding

      Parameters

      • binding: Binding

        The binding key or class constructor to resolve

      • OptionalruntimeValues: any[]

        Optional array of runtime values for constructor dependencies

      • OptionalcreateError: ErrorCreator

        Optional custom error creator function

      Returns Promise<Make<Binding>>

      await container.make('route')
      await container.make(Database)
      await container.make(UsersController, [request, response])
    • Call a method on an object by injecting its dependencies. The method dependencies are resolved in the same manner as a class constructor dependencies.

      Type Parameters

      • Value extends Record<any, any>
      • Method extends string | number | symbol

      Parameters

      • value: Value

        The object instance containing the method

      • method: Method

        The method name to call

      • OptionalruntimeValues: any[]

        Optional array of runtime values for method dependencies

      • OptionalcreateError: ErrorCreator

        Optional custom error creator function

      Returns Promise<ReturnType<Value[Method]>>

      const controller = await container.make(UsersController)
      await container.call(controller, 'index')
    • Register an alias for a binding. The value can be a reference to an existing binding or to a class constructor that will instantiate to the same value as the alias.

      Type Parameters

      • Alias extends string | number | symbol

      Parameters

      • alias: Alias extends string | symbol ? Alias : never

        The alias name (must be string or symbol)

      • value:
            | AbstractConstructor<KnownBindings[Alias]>
            | Exclude<
                {
                    [K in string
                    | number
                    | symbol]: KnownBindings[K] extends KnownBindings[Alias] ? K : never
                }[keyof KnownBindings],
                Alias,
            >

        The constructor or binding key this alias points to

      Returns void

      container.alias('db', Database)
      await container.make('db') // returns Database instance
    • Register a binding inside the container. The method receives a key-value pair.

      • Key can be a string, symbol or a constructor.
      • The value is always a factory function to construct the dependency.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      Returns void

      container.bind('route', () => new Route())
      await container.make('route')
      container.bind(Route, () => new Route())
      await container.make(Route)
      const routeSymbol = Symbol('route')
      container.bind(routeSymbol, () => new Route())
      await container.make(routeSymbol)
    • Register a binding inside the container. The method receives a key-value pair.

      • Key can be a string, symbol or a constructor.
      • The value is always a factory function to construct the dependency.

      Type Parameters

      • Binding extends AbstractConstructor<any>

      Parameters

      Returns void

      container.bind('route', () => new Route())
      await container.make('route')
      container.bind(Route, () => new Route())
      await container.make(Route)
      const routeSymbol = Symbol('route')
      container.bind(routeSymbol, () => new Route())
      await container.make(routeSymbol)
    • Register a binding as a value. Unlike bind() and singleton(), this method accepts the resolved value directly instead of a factory function.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      • binding: Binding extends string | symbol ? Binding : never

        The binding key (string, symbol, or class constructor)

      • value: KnownBindings[Binding]

        The pre-resolved value to bind

      Returns void

      const route = new Route()
      container.bindValue(Route, route)
      container.bindValue('config', { debug: true })
      
    • Register a binding as a value. Unlike bind() and singleton(), this method accepts the resolved value directly instead of a factory function.

      Type Parameters

      • Binding extends AbstractConstructor<any>

      Parameters

      • binding: Binding

        The binding key (string, symbol, or class constructor)

      • value: InstanceType<Binding>

        The pre-resolved value to bind

      Returns void

      const route = new Route()
      container.bindValue(Route, route)
      container.bindValue('config', { debug: true })
      
    • Register a binding as a singleton. The singleton method is same as the bind method, but the factory function is invoked only once and the result is cached for subsequent resolutions.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      Returns void

      container.singleton('route', () => new Route())
      await container.make('route')
      container.singleton(Route, () => new Route())
      await container.make(Route)
      const routeSymbol = Symbol('route')
      container.singleton(routeSymbol, () => new Route())
      await container.make(routeSymbol)
    • Register a binding as a singleton. The singleton method is same as the bind method, but the factory function is invoked only once and the result is cached for subsequent resolutions.

      Type Parameters

      • Binding extends AbstractConstructor<any>

      Parameters

      Returns void

      container.singleton('route', () => new Route())
      await container.make('route')
      container.singleton(Route, () => new Route())
      await container.make(Route)
      const routeSymbol = Symbol('route')
      container.singleton(routeSymbol, () => new Route())
      await container.make(routeSymbol)
    • Define a fake implementation for a binding or a class constructor. Swaps have the highest priority when resolving dependencies from the container. Useful for testing.

      Type Parameters

      • Binding extends AbstractConstructor<any>

      Parameters

      Returns void

      container.swap(Database, () => new MockDatabase())
      const db = await container.make(Database) // returns MockDatabase
    • Restore binding by removing its swap

      Parameters

      • binding: AbstractConstructor<any>

        The class constructor to restore

      Returns void

      container.restore(Database)
      
    • Restore mentioned or all bindings by removing their swaps

      Parameters

      • Optionalbindings: AbstractConstructor<any>[]

        Optional array of class constructors to restore. If not provided, all swaps are removed

      Returns void

      container.restoreAll([Database, Cache])
      
      container.restoreAll() // Restore all swaps
      
    • Define hooks to be executed after a binding has been resolved from the container.

      The hooks are executed for:

      • Bindings
      • Only once for singletons
      • Class constructors

      Hooks are not executed for direct values registered with the container.

      Type Parameters

      • Binding extends string | number | symbol

      Parameters

      Returns void

      container.resolving('database', async (db, resolver) => {
      await db.connect()
      })
      container.resolving(Database, async (db, resolver) => {
      await db.connect()
      })
    • Define hooks to be executed after a binding has been resolved from the container.

      The hooks are executed for:

      • Bindings
      • Only once for singletons
      • Class constructors

      Hooks are not executed for direct values registered with the container.

      Type Parameters

      • Binding extends AbstractConstructor<any>

      Parameters

      Returns void

      container.resolving('database', async (db, resolver) => {
      await db.connect()
      })
      container.resolving(Database, async (db, resolver) => {
      await db.connect()
      })
    • Create a contextual builder to define contextual bindings. Contextual bindings allow you to specify different implementations for a dependency based on which class is asking for it.

      Parameters

      • parent: Constructor<any>

        The class constructor that will receive the contextual binding

      Returns ContextBindingsBuilder<KnownBindings, AbstractConstructor<any>>

      container
      .when(UsersController)
      .asksFor(Hash)
      .provide(() => new Argon2())
    • Create a conditional builder to define bindings that are only used when the condition returns true. The condition is evaluated on every resolution and receives the resolver performing it.

      Unlike contextual bindings, which are scoped to a parent class, conditional bindings apply to every resolution of the binding key.

      Parameters

      Returns ConditionalBindingsBuilder<KnownBindings>

      container
      .if(async (resolver) => {
      if (!resolver.hasBinding(HttpContext)) {
      return false
      }
      const ctx = await resolver.make(HttpContext)
      return ctx.auth.user?.featureFlags.includes('new-payment') === true
      })
      .bind(PaymentGateway, (resolver) => resolver.make(BetaPaymentGateway))
    • Add a contextual binding for a given class constructor. A contextual binding takes a parent, parent's dependency and a callback to resolve the dependency.

      For example:

      • When "UsersController"
      • Asks for "Hash class"
      • Provide "Argon2" implementation

      Type Parameters

      • Binding extends AbstractConstructor<any>

      Parameters

      • parent: Constructor<any>

        The class constructor that will receive the contextual binding

      • binding: Binding

        The dependency class that the parent asks for

      • resolver: BindingResolver<KnownBindings, Make<Binding>>

        Factory function to resolve the contextual binding

      Returns void

      container.contextualBinding(
      UsersController,
      Hash,
      () => new Argon2()
      )