API reference
Container API.
The public API is intentionally small: register services, resolve them, create scopes, override dependencies in tests, and validate wiring.
Registration
| Method | Purpose |
|---|---|
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
resolve(interface, name=None)resolves one service.resolve_all(interface, name=None)resolves registered implementations.call(func, **overrides)calls a function with its annotated parameters injected;acallis the async form.create_scope()creates a request, job, or message lifetime (usable as awithblock; finalizes scoped resources).
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
validate()returns validation errors.assert_valid()raisesContainerValidationExceptionif validation fails.
Async
Async factories (async def) and async-generator resources use the
same add_*_factory methods and resolve through the async API.
await container.aresolve(interface, name=None)resolves one service, awaiting any async factory in the graph.async with container.ascope() as scope:opens anAsyncScope; scoped/transient async resources resolved withawait scope.aresolve(...)are finalized LIFO on exit.await container.aclose()finalizes singleton async resources at shutdown.
The synchronous resolve() raises
AsyncResolutionRequiredException if the graph needs async work.
See async resolution.
Decorators and markers
@inject— mark a method for property injection.@injectable(lifestyle="transient", name=None, provides=None)— mark a class forcontainer.scan().Named("name")— insideAnnotated[T, Named("name")], selects a named registration.
Integrations
injex.ext.fastapi:setup_injex(app, container)+Provide(T)— see FastAPI. Installinjex[fastapi].injex.ext.cli:Inject()+wire(container)for Typer/Click commands.
Exceptions
ServiceNotRegisteredException, CyclicDependencyException,
MissingTypeAnnotationException, InvalidLifestyleException,
ContainerValidationException, AsyncResolutionRequiredException,
and PropertyInjectionException inherit from DIException.