FastAPI Dependency Injection: Managing Sub-dependency Cache in Complex Request Lifecycles
0 reputation · 26 Jun 2022, 07:18 UTC
Dependency Resolution and Caching
FastAPI utilizes the Depends class to manage resources, where sub-dependencies are cached by default within a single request scope to prevent redundant executions. This behavior ensures that if multiple dependencies require the same database session or security scheme, the logic executes only once per request.
Scope and Overrides
While app.dependency_overrides allows for replacing production logic with mocks during testing, the interaction between cached sub-dependencies and nested dependency trees can create ambiguity when specific request-level state changes are required mid-lifecycle.
There is a need to clarify the behavior when the use_cache parameter is set to False in a deeply nested hierarchy. It is unclear if disabling the cache at a top-level dependency propagates to all its child dependencies or if each node in the tree must be explicitly configured.
- Does setting
use_cache=Falseon a parent dependency force the re-execution of all nested sub-dependencies? - How does the dependency resolver prioritize
use_cachesettings when the same dependency is required by two different branches of the tree with conflicting cache configurations?