linkd.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[..., utils.MaybeAwaitable[T]], *, teardown: Callable[[T], utils.MaybeAwaitable[None]] | None = None, lifetime: Lifetime.SINGLETON = graph.Lifetime.SINGLETON) None[source]¶
- add_factory(typ: type[T], factory: Callable[..., utils.MaybeAwaitable[T]], *, lifetime: Lifetime.PROTOTYPE) None
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. May only be specified when lifetime is not set toPROTOTYPE.lifetime – The lifetime of the dependency. Defaults to
SINGLETON.
- Returns:
- Raises:
ValueError – If ‘lifetime’ is set to ‘PROTOTYPE’ and ‘teardown’ is specified.
CircularDependencyException – If the factory requires itself as a dependency.
See also
linkd.registry.Registry.register_factory()for factory and teardown function spec.Added in version 0.1.0: The ‘lifetime’ parameter.
- add_value(typ: type[T], value: T, *, teardown: Callable[[T], utils.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:
See also
linkd.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:
ContainerClosedException – If the container is closed.
CircularDependencyException – If the dependency cannot be satisfied due to a circular dependency with itself or a sub-dependency.
DependencyNotSatisfiableException – If the dependency cannot be satisfied for any other reason.