The Dependency Injection Container¶
Containers serve as a central place to store and manage providers. You also define your dependency graph in the containers.
While providers can be defined outside of containers with that depends, this is not recommended if you want to use any context features
Quickstart¶
Define a container by subclassing BaseContainer and define your providers as class attributes.
Then you can build your dependency graph within the container:
from that_depends import providers
class Container(BaseContainer):
config = providers.Singleton(Config)
session = providers.Factory(create_db_session, config=config.db) # (1)!
user_repository = providers.Factory(
UserRepository,
session=session.cast, # (3)!
config.users
) # (2)!
- The configuration will be resolved and then the
.dbattribute will be passed to thecreate_db_sessioncreator as a keyword argument when resolving thesessionprovider. - Depends on both the session and configuration providers.
- Providers have the
castproperty that will change their type to the return type of their creator, use it to prevent type errors.