API reference

Container API.

The public API is intentionally small: register services, resolve them, create scopes, override dependencies in tests, and validate wiring.

Registration

MethodPurpose
add_singleton(interface, implementation=None, name=None)Reuse one instance for the app lifetime.
add_transient(interface, implementation=None, name=None)Create a new instance on each resolve.
add_scoped(interface, implementation=None, name=None)Reuse one instance inside a scope.
add_instance(interface, instance, name=None)Register an already built object.
add_singleton_factory / add_transient_factory / add_scoped_factory(interface, factory, name=None)Custom construction; a generator factory becomes a resource with teardown.
register / register_factory(interface, …, lifestyle="transient", name=None)General forms the helpers wrap.
scan(*modules_or_iterables)Register every @injectable class found.

Resolving

To inject a named registration into a constructor, annotate it Annotated[T, Named("primary")].

Overrides

with container.override(PaymentGateway, instance=fake_gateway):
    checkout = container.resolve(Checkout)

Validation

Async

Async factories (async def) and async-generator resources use the same add_*_factory methods and resolve through the async API.

The synchronous resolve() raises AsyncResolutionRequiredException if the graph needs async work. See async resolution.

Decorators and markers

Integrations

Exceptions

ServiceNotRegisteredException, CyclicDependencyException, MissingTypeAnnotationException, InvalidLifestyleException, ContainerValidationException, AsyncResolutionRequiredException, and PropertyInjectionException inherit from DIException.