modern-python / fastapi-sqlalchemy-template

Dockerized web application with DI on FastAPI, sqlalchemy2, PostgreSQL
MIT License
94 stars 17 forks source link

Question about IOC DI #24

Closed MrNaif2018 closed 1 month ago

MrNaif2018 commented 1 month ago

Hi! I stumbled across your repository a few months ago and it was an amazing find! Thank you! My current project is stuck on gino since times when sqlalchemy didn't have async support and I'm looking to migrate to sqlalchemy 2.0+ for better support in the future, but what I didn't like is passing session around in every function.

I liked that you created a BaseModel, which fetched session via a contextvar, I believe that's how gino worked as well.

But since 4 months ago you have changed the logic to use IOC container for dependency injection: if you have time, could you please tell why it's better? I know some people who tell contextvars is almost like a global var, but sometimes I think it's useful to avoid passing objects everywhere.

Like, if to use this IOC container and you would e.g. have a second process (background process processing tasks sent from fastapi app for example) which isn't started by fastapi (so can't use Depends), would this DI still work?

lesnik512 commented 1 month ago

@MrNaif2018 Hi! Glad to hear)

About DI, first of all it helps to avoid passing objects by allowing to build any dependency in one line

And by the way in DI contextvars are still used under the hood for session management in context resource.

Second point, is that DI can be used not only in API, but anywhere in other parts of your app, including tests and some background workers by injecting in functions arguments or just resolving dependencies in your code

MrNaif2018 commented 1 month ago

Thank you very much! It's way more clear now