modern-python / that-depends

DI-framework, inspired by python-dependency-injector, but without wiring. Python 3.12 is supported
https://that-depends.readthedocs.io/
MIT License
156 stars 12 forks source link

Is that-depends possible to support inject almost everywhere without wiring? #39

Closed rumbarum closed 4 months ago

rumbarum commented 4 months ago

I used to use dependency-injector(di) for inject config, complex obj or so on everywhere, like described on their docs.

As I know, wiring is a key action which reads code and replace initial dummy obj (Provide(...)) to real one(injecting object) before run python process. I also have experienced injecting from central Container instance made circular import error if i use container directly over related modules and that case only literal inject works supported by wiring.

Will that-depends provide similar usage covering this case without wiring?

lesnik512 commented 4 months ago

Hello, @rumbarum

  1. In case of that-depends there is no wiring, so such thing won't work and I'm not sure that it's needed:
service: Service = Provide[Container.service]

You can just build dependency anywhere in you code like this

  1. About circular import error: I personally think that circular import error should be resolved by refactoring code instead of hiding it by wiring of DI.
rumbarum commented 4 months ago

@lesnik512 Thank you for your answer.

This is my use case of inject something directly. I could wrap it by something callable and inject it as args. But this is much simpler. So I applied this pattern when necessary.


session: async_scoped_session = Provide["session"]

class SQLAlchemyMiddleware:
    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        session_id = str(uuid4())
        context = set_session_context(session_id=session_id)
        try:
            await self.app(scope, receive, send)
        except Exception as e:
            raise e
        finally:
            await session.remove()
            reset_session_context(context=context)

Anyway, I will try review your package.