Scope chain violation¶
This error fires when a provider depends on another provider with a shorter lifetime than its own. APP-scoped factories cannot consume REQUEST-scoped dependencies, because the REQUEST instance would outlive its request.
Understanding the error¶
You'll see something like:
ValidationFailedError: Container.validate() found 1 issue(s): InvalidScopeDependencyError
- Provider UserCache (scope APP) declares parameter 'session' typed as a provider of Session at deeper scope REQUEST. A provider cannot depend on a deeper-scoped provider.
The fix is always to make the depender's scope equal to or shorter than the dependee's. In the example above, UserCache should be REQUEST-scoped, not APP-scoped.
Common cases¶
- Forgot
scope=Scope.REQUESTon a repository. Defaults toScope.APPif omitted. A repository that holds a session needsscope=Scope.REQUEST. - Helper or utility provider auto-defaulted to APP. Same as above — anything that consumes the session is REQUEST-scoped.
- Choice factory consuming the request. A factory that depends on the framework's
Requestis REQUEST-scoped; you cannot resolve it from the APP container.
How to fix¶
Bump the depender's scope:
class Dependencies(Group):
session = providers.Factory(
scope=Scope.REQUEST,
creator=create_session,
cache_settings=providers.CacheSettings(finalizer=close_session),
)
# ❌ APP-scoped — fails validation
user_repository = providers.Factory(creator=UserRepository)
# ✅ REQUEST-scoped — matches session's lifetime
user_repository = providers.Factory(
scope=Scope.REQUEST,
creator=UserRepository,
)
Detect early¶
Container(groups=[...], validate=True) runs this check at startup, before the first request. Always pass validate=True — the diagnostic is much clearer than the runtime symptoms.