Skip to content

Commit

Permalink
Bind RequestScopeFactory so that auto_bind=False does not break
Browse files Browse the repository at this point in the history
  • Loading branch information
matyasrichter committed Feb 3, 2024
1 parent 9ef0b40 commit 549a9c2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
3 changes: 2 additions & 1 deletion fastapi_injector/attach.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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:
Expand Down
25 changes: 25 additions & 0 deletions tests/test_request_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 549a9c2

Please sign in to comment.