Service Container
Register and resolve your application's services with Alata's dependency injection container.
The service container is the registry at the heart of every Alata application: providers bind services into it during boot, and the rest of your code resolves them by name. It keeps construction logic in one place, makes dependencies lazy by default, and lets tests swap implementations without patching imports.
The container handle
Everywhere in your application, import the same handle:
from alata.container import container
config = container.make("config")
log = container.make("log")The container handle resolves services from the active application. In tests, use ServiceContainer.set_instance() to substitute a container with test bindings, then restore the previous one:
from alata.container import ServiceContainer, container, current_container
test_container = ServiceContainer()
test_container.instance("mailer", FakeMailer())
previous = current_container()
ServiceContainer.set_instance(test_container)
try:
# every `container.make("mailer")` in production code now returns FakeMailer
assert container.make("mailer") is test_container.make("mailer")
finally:
ServiceContainer.set_instance(previous)current_container() returns the active container.
Binding services
Bindings are normally registered inside a service provider's register() method. There are three binding styles.
Singletons
singleton(name, factory) registers a lazy singleton: the factory runs once, on the first make(), and the result is cached for every subsequent call.
container.singleton("mailer", lambda: Mailer(api_key=settings.MAIL_KEY))
a = container.make("mailer")
b = container.make("mailer")
assert a is b # factory ran exactly onceA singleton factory that returns None is not cached — the factory is retried on the next make().
You may pass arguments on a singleton's first resolution (container.make("svc", val="configured")), but passing arguments to an already-resolved singleton raises ValueError.
Factories
bind(name, factory) registers a plain factory: it runs on every make(), returning a fresh instance each time.
container.bind("report", lambda: ReportBuilder())
a = container.make("report")
b = container.make("report")
assert a is not b # new instance per callInstances
instance(name, value) registers a pre-built value — an eager singleton. The framework uses this for Phase-0 bindings like "config" and "settings", and providers use it when the object already exists at registration time.
storage = Storage(app).set_configuration(disks)
container.instance("storage", storage)Resolving services
make(name) resolves a binding, checking in this order:
- Pre-built instances (from
instance()) - Lazy singletons (from
singleton(), cached after the first call) - Factories (from
bind(), fresh each call)
An unregistered name raises KeyError. Use has(name) to check first, and registered() to list every binding name:
if container.has("cache"):
cache = container.make("cache")
print(container.registered()) # ['cache', 'config', 'engine', 'events', ...]The registration guard
During Phase 1 of the boot lifecycle — while providers are running register() — the container blocks resolution. Any make() call for a non-instance binding raises immediately:
RuntimeError: Cannot resolve 'cache' during Phase 1 (register).
Move resolution logic to a boot() method.This enforces the provider contract: register() binds, boot() resolves. Pre-built instances are exempt because they are plain values that are always safe to read — which is exactly why Phase 0 binds "config" and "settings" as instances before any provider runs.
Type-based resolution and @inject
Besides string names, the container can map classes to bindings for type-driven resolution:
from alata.container import container, inject
from alata.log_manager import LogManager
# In a provider's register():
container.bind_type(LogManager, "log")
# Anywhere:
log = container.resolve(LogManager) # delegates to make("log")
container.has_type(LogManager) # TrueThe @inject decorator builds on the type map: it inspects a function's type hints and auto-fills any parameter whose annotated type is registered. Parameters you pass explicitly are never overridden, and both sync and async functions are supported.
from alata.container import inject
from alata.log_manager import LogManager
@inject
def handle_search(query: str, log: LogManager):
log.info(f"Searching for {query}")
handle_search("python developer") # 'log' is auto-injectedresolve() on an unmapped type raises KeyError telling you to call bind_type() first.
Resetting: flush()
flush() removes a container's bindings and boot state. Use it to clean up an isolated test container, then restore the previous container as shown above. The testing guide provides a reusable fixture.
Do not flush the application's shared container while it is serving requests or between tests that reuse that application. Re-importing its bootstrap module does not reconstruct it.
API reference
| Member | Description |
|---|---|
singleton(name, factory) | Lazy singleton — factory runs once, result cached |
bind(name, factory) | Factory — runs on every make() |
instance(name, value) | Pre-built value (eager singleton) |
make(name, *args, **kwargs) | Resolve by name; instances → singletons → factories |
has(name) | Whether a binding exists under any style |
registered() | Sorted list of all binding names |
bind_type(cls, name) / resolve(cls) / has_type(cls) | Class-to-binding mapping for typed resolution |
flush() | Reset the container for reuse in tests |
booted / mark_booted() | Boot-cycle state |
ServiceContainer.set_instance(c) / get_instance() | Promote / fetch the process's current container |
current_container() | The container the proxy currently targets |
@inject | Auto-fill parameters from type hints |
To see who populates the container and when, continue with service providers and the application lifecycle.