From 549a9c253468c8916fff64813448d479bb1f4d8a Mon Sep 17 00:00:00 2001 From: Matyas Richter Date: Sat, 3 Feb 2024 22:46:32 +0900 Subject: [PATCH] Bind RequestScopeFactory so that auto_bind=False does not break --- fastapi_injector/attach.py | 3 ++- tests/test_request_scope.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/fastapi_injector/attach.py b/fastapi_injector/attach.py index ec93007..284f41a 100644 --- a/fastapi_injector/attach.py +++ b/fastapi_injector/attach.py @@ -2,7 +2,7 @@ from injector import Injector, InstanceProvider, singleton from fastapi_injector.exceptions import InjectorNotAttached -from fastapi_injector.request_scope import RequestScopeOptions +from fastapi_injector.request_scope import RequestScopeFactory, RequestScopeOptions def attach_injector( @@ -17,6 +17,7 @@ def attach_injector( injector.binder.bind( RequestScopeOptions, InstanceProvider(options), scope=singleton ) + injector.binder.bind(RequestScopeFactory, to=RequestScopeFactory, scope=singleton) def get_injector_instance(app: FastAPI) -> Injector: diff --git a/tests/test_request_scope.py b/tests/test_request_scope.py index 97b3420..8e0c234 100644 --- a/tests/test_request_scope.py +++ b/tests/test_request_scope.py @@ -235,6 +235,31 @@ class DummyImpl: assert dummy1 is not dummy3 +async def test_works_without_auto_bind(): + class DummyInterface: + pass + + class DummyImpl: + pass + + inj = Injector(auto_bind=False) + app = FastAPI() + app.add_middleware(InjectorMiddleware, injector=inj) + attach_injector(app, inj) + inj.binder.bind(DummyInterface, to=DummyImpl, scope=request_scope) + + @app.get("/") + def get_root( + dummy: DummyInterface = Injected(DummyInterface), + dummy2: DummyInterface = Injected(DummyInterface), + ): + assert dummy is dummy2 + + async with httpx.AsyncClient(app=app, base_url="http://test") as client: + r = await client.get("/") + assert r.status_code == status.HTTP_200_OK + + class DummyContextManager: UNENTERED = object() ENTERED = object()