lightbulb.di.container

class Container(registry: registry_.Registry, *, parent: Container | None = None, tag: Context | None = None)[source]

A container for managing and supplying dependencies.

Parameters:
  • registry – The registry of dependencies supply-able by this container.

  • parent – The parent container. Defaults to None.

add_factory(typ: type[T], factory: Callable[..., lb_types.MaybeAwaitable[T]], *, teardown: Callable[[T], lb_types.MaybeAwaitable[None]] | None = None) None[source]

Adds the given factory as an ephemeral dependency to this container. This dependency is only accessible from contexts including this container and will be cleaned up when the container is closed.

Parameters:
  • typ – The type to register the dependency as.

  • factory – The factory used to create the dependency.

  • teardown – The teardown function to be called when the container is closed. Defaults to None.

Returns:

None

See also

lightbulb.di.registry.Registry.register_factory() for factory and teardown function spec.

add_value(typ: type[T], value: T, *, teardown: Callable[[T], lb_types.MaybeAwaitable[None]] | None = None) None[source]

Adds the given value as an ephemeral dependency to this container. This dependency is only accessible from contexts including this container and will be cleaned up when the container is closed.

Parameters:
  • typ – The type to register the dependency as.

  • value – The value to use for the dependency.

  • teardown – The teardown function to be called when the container is closed. Defaults to None.

Returns:

None

See also

lightbulb.di.registry.Registry.register_value() for teardown function spec.

async close() None[source]

Closes the container, running teardown procedures for each created dependency belonging to this container.

async get(type_: type[T], /) T[source]
async get(type_: Any, /) Any

Get a dependency from this container, instantiating it and sub-dependencies if necessary.

Parameters:

type – The type used when registering the dependency.

Returns:

The dependency for the given type.

Raises: