Container
provide.foundation.hub.container
¶
TODO: Add module docstring.
Classes¶
Container
¶
Dependency Injection Container.
A focused API for dependency injection patterns, wrapping the Hub with a simpler interface for type-based registration and resolution.
This container follows the Composition Root pattern where all dependencies are registered at application startup and then resolved as needed.
Example
container = Container() container.register(DatabaseClient, db_instance) container.register(HTTPClient, http_instance)
Resolve with automatic dependency injection¶
service = container.resolve(MyService)
MyService.init(db, http) called automatically¶
Pattern
The Container is designed for the Composition Root pattern: 1. Create container at app startup (main.py) 2. Register all core dependencies 3. Resolve application entry points 4. Pass dependencies explicitly (no global access)
This matches the idiomatic patterns in Go and Rust, making it easier to adopt for developers from those ecosystems.
Initialize the DI container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hub
|
Hub | None
|
Optional Hub instance (creates new if not provided) |
None
|
registry
|
Registry | None
|
Optional Registry instance (creates new if not provided) |
None
|
Source code in provide/foundation/hub/container.py
Functions¶
__enter__
¶
Context manager entry.
Example
with Container() as container: ... container.register(Database, db) ... service = container.resolve(MyService)
__exit__
¶
clear
¶
Clear all registered dependencies.
Warning
This clears the underlying Hub registry. Use with caution.
get
¶
Get a registered instance by type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_hint
|
type[T]
|
Type to retrieve |
required |
Returns:
| Type | Description |
|---|---|
T | None
|
Registered instance or None if not found |
Example
db = container.get(Database)
Source code in provide/foundation/hub/container.py
has
¶
register
¶
Register a dependency by type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_hint
|
type[T]
|
Type to register under |
required |
instance
|
T
|
Instance to register |
required |
name
|
str | None
|
Optional name for named registration |
None
|
Returns:
| Type | Description |
|---|---|
Container
|
Self for method chaining |
Example
container.register(Database, db).register(Cache, cache)
Source code in provide/foundation/hub/container.py
resolve
¶
Resolve a class with dependency injection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[T]
|
Class to instantiate |
required |
**overrides
|
Any
|
Explicitly provided dependencies |
{}
|
Returns:
| Type | Description |
|---|---|
T
|
New instance with dependencies injected |
Example
service = container.resolve(MyService)
Or with overrides:¶
service = container.resolve(MyService, logger=custom_logger)