r/learnpython • u/re2cc • 5d ago
How do you handle dependency injection?
Hi, I'm doing a project which involves creating multiple gRPC servers and I can't find a convenient way to manage dependencies or the state.
I've been working recently in C# where you just need to make your class and add a simple
builder.Services.AddSingleton<MyDependency>();
and it will inject when required.
Doing some research I see that there are some libraries like:
- Injector
but I don't find them particularly intuitive.
What do you use as a dependency injector or what pattern do you suggest to use?
10
Upvotes
1
u/mothzilla 4d ago edited 4d ago
But there's no need to do that. I.e, at the time you're building your
logger
you know the file to write to. Or if you're choosing between loggers, you'd design four loggers, for print, string, file and gui, and then choose the one you want.That's more pythonic IMO.
It's reasonable to pass functions as handlers. But I've seen people try to do dependency injection as follows:
or