django-ninja
django-ninja copied to clipboard
Ninja + dependency injector?
Anyone else trying to implement the dependency injector package? Would love some examples on y'alls implementations.
Atm I have been adding it under the main project next to asgi and added asynccontext with lifespan into the asgi file. I might need to dig deeper into ninja to understand the full lifecycle. Anyways any tips and tricks or implementation examples would be much appreciated :)
If I understand correctly what you're trying to achieve, you might find django-ninja-extra interesting. It has built-in support for Injector, is compatible with django-injector, and handles automatic dependency resolution.
Even if it's not exactly what you're looking for, it could serve as a useful reference or give you some ideas. HTH
Anydi package has integration with Django-Ninja, so you can easier add it to your project
django ninja is not any differen from any other django project app - no built-in support are planned for now
I don't think we need a third party package to do dependency injection in ninja's context. Just the ability to do this would be tremendously helpful when writing tests:
@router.post("/")
def create_user(request, payload: UserCreateSchema, user_service: Annotated[UserService, Depends(get_user_service)]):
return user_service.create_user(payload.username)
And in test:
def test_create_user():
response = TestClient(router).post("/", dependencies={"user_service": MockUserService})
...
This is inspired from fastapi and i think it can be implemented in Ninja with minimal changes.
I can write up a PR for this, what do you think @vitalik ?
well Depends part in FastAPI is the ugliest part IMO - and they have it basically to make easier to pass database connections or users
but redability becomes ugly
now look at this example:
@router.post("/")
def create_user(request, payload: UserCreateSchema):
user_service: UserService = get_user_service()
return user_service.create_user(payload.username)
clean and beatuifull
and you can extend get_user_service with any DI framework you like