django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

Ninja + dependency injector?

Open devjerry0 opened this issue 9 months ago • 2 comments

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 :)

devjerry0 avatar Feb 07 '25 15:02 devjerry0

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

paolodina avatar Feb 10 '25 22:02 paolodina

Anydi package has integration with Django-Ninja, so you can easier add it to your project

ALittleMoron avatar Mar 25 '25 13:03 ALittleMoron

django ninja is not any differen from any other django project app - no built-in support are planned for now

vitalik avatar Oct 14 '25 15:10 vitalik

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 ?

tu-pm avatar Nov 18 '25 02:11 tu-pm

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

vitalik avatar Nov 18 '25 12:11 vitalik