Client Server DI Design with dependency_injector #833
Unanswered
sebastianjanisch
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I come from a Java Spring beans word where dependencies would be defined in code and then when the application boots you obtain whatever bean you need from the application context and are on your way.
I have been coding in Python for quite some time and was always wondering what the proper pythonic way of DI is. I am using FastAPI a lot but their DI solution doesn't seem to be 'true' in a sense that when I specify a dependency as
my_arg: Annotated[SomeService, Depends(deps.some_service))
I might be logically decoupled from the creation of my service object but still I have a direct and hard link to the code that creates the concrete service.In my setup I don't know what the concrete service is at the time the application is built, I only know it at runtime. I found dependency_injector which seems to come to the rescue but I am wondering about best practices for my setup.
I am developing a classic client server architecture with FastAPI and a python client stub. It consists of these projects:
impl
,client
,rest
andgui
depends onapi
.rest
depends onimpl
,gui
depends onclient
.Both
client
andimpl
implement the same interfaces exposed byapi
, say aUserService
. Obviouslyimpl
implements the real logic with databases whileclient
just fires http requests which eventually hit therest
endpoints.It kind of looks like so
So far so good. The question is how do I wire all this together neatly (for reference we use reflex.dev for GUI which is all python). (also one thing I can't get to work is @Inject into
cbv
fast api views).I want to be dynamic about what
UserService
gets injected into the GUI. It's determined at runtime.The setup I'd like to end up with is where containers can be contributed from various parts of the application. These containers contribute providers for different services. Say I have
ContainerA
andContainerB
andContainerB
brings inUserService
. What do I specify in my dependency?I can't put
ContainerB
in there because I don't know yet which container supplies. I guess what I am trying to figure out is how to get the Spring like behavior where dependencies are identified by the class and interface they implement (if there is only one candidate for a given interface) and if a method depends on that service it doesn't matter where it came from, it will be wired in by the container.I maybe thinking about this the wrong way but I wanted to post this here to get some feedback on what the right approach is.
Beta Was this translation helpful? Give feedback.
All reactions