diff --git a/docs/main/changelog.rst b/docs/main/changelog.rst index eebf8b67..81ece652 100644 --- a/docs/main/changelog.rst +++ b/docs/main/changelog.rst @@ -7,6 +7,10 @@ that were made in every particular version. From version 0.7.6 *Dependency Injector* framework strictly follows `Semantic versioning`_ +Develop +------- +- Improve ``FastAPI`` integration: handle ``Depends(Provide[...])``. + 4.4.0 ----- - Add ``@inject`` decorator. It helps to fix a number of wiring bugs and make wiring be more resilient. diff --git a/src/dependency_injector/wiring.py b/src/dependency_injector/wiring.py index 1ba73639..6752f106 100644 --- a/src/dependency_injector/wiring.py +++ b/src/dependency_injector/wiring.py @@ -27,6 +27,13 @@ else: ... +try: + from fastapi.params import Depends as FastAPIDepends + fastapi_installed = True +except ImportError: + fastapi_installed = False + + from . import providers @@ -320,10 +327,15 @@ def _fetch_reference_injections( injections = {} closing = {} for parameter_name, parameter in signature.parameters.items(): - if not isinstance(parameter.default, _Marker): + if not isinstance(parameter.default, _Marker) \ + and not _is_fastapi_depends(parameter.default): continue + marker = parameter.default + if _is_fastapi_depends(marker): + marker = marker.dependency + if isinstance(marker, Closing): marker = marker.provider closing[parameter_name] = marker @@ -435,6 +447,10 @@ def _is_fastapi_default_arg_injection(injection, kwargs): return injection in kwargs and isinstance(kwargs[injection], _Marker) +def _is_fastapi_depends(param: Any) -> bool: + return fastapi_installed and isinstance(param, FastAPIDepends) + + def _is_patched(fn): return getattr(fn, '__wired__', False) is True @@ -459,6 +475,9 @@ class _Marker(Generic[T], metaclass=ClassGetItemMeta): def __class_getitem__(cls, item) -> T: return cls(item) + def __call__(self) -> T: + return self + class Provide(_Marker): ...