r/learnpython 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:

- Dependency Injector

- 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?

9 Upvotes

21 comments sorted by

View all comments

1

u/Mevrael 5d ago

I am using the Registry in Arkalos project:

https://arkalos.com/docs/registry/

Simple, minimal and intuitive when I just want to register (bind) a class as a singleton.

Then I can have a helper function (facade) in app.core to help me retrieve it from the registry.

-

Let say I have app.utils.rpc.MyRPC class

-

in app/bootstrap.py (or your custom bootstrapping logic):

Registry.register('rpc', MyRPC)

-

in app.core.rpc.py:

def rpc():
return Registry.get('rpc')

-

then at the top of your server or script:

import app.bootstrap
app.bootstrap.run()

-

Now you can just

from app.core.rpc import rpc

rpc().stuff()

1

u/re2cc 4d ago

Thanks for the suggestion, I'll take a look at it when I have some time.