Please feel free to have a look at this one. You can do a lot more stuff; this is just a foundation.
The main difference is that lifespan runs once when the app starts and once when it shuts down. DI deps usually run per request or whenever you inject them. Lifespan’s great for stuff you want to set up once and keep around for the whole lifetime of the app.
EDIT: Reddit keeps blocking my comment, I guess because of the code block. I tried at least 1000 times to write this :D. It shouldn't have been that hard!
I usually just create these things as async tasks and cancel them after the yield. Also sometimes my classes need the eventloop e.g to delegate some synchronous calls to an executor and if they have the reference to the current eventloop that reduces the callstack overhead over calling asyncio.to_thread() (because that calls get_event_loop or get_running_loop under the hood, can’t remember which one), so I initialize them in the lifespan method
View all comments
Show parent comment
1
u/Gushys Aug 14 '25
Curious on how this looks, any documentation or examples on how this is done? I would think that the dependency injection already kind of handles this