python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Auto wiring

Open sparky2708 opened this issue 1 year ago • 3 comments
trafficstars

Is there a way to auto-wire?

e.g.:

class B: @inject def init(self, registered_class: IRegisteredClass): ...

Why do I need to specify Provider[...]. If all are wired why not just auto-wire IRegisteredClass interface to the object that is registered in some container that implements this interface?

sparky2708 avatar Oct 09 '24 20:10 sparky2708

If this seems viable for the author to have, I can PR this

I neither checked the code nor used the package, so the decision is mainly up to people who know it very well, I'm mainly looking to contribute in DI projects since I'm a fan of the pattern

LeOndaz avatar Oct 12 '24 04:10 LeOndaz

I opened issues looking for some context on this specific question as I assumed it's something that can be done but I don't know how. My thinking as a DI user is that, if I configure/describe the dependencies and their relationships in container, then I can 'just' request the type (with qualifiers etc) and get it on a call-site. If I need to define relationships in a container, and then reference that container in a call-site to describe where/how dependences are to be provided, it kind of defeats the purpose of DI - which is to leave config to container and have 'pure' logic methods/functions that 'just get' what they need.

dbarwacz avatar Dec 12 '24 12:12 dbarwacz

@sparky2708

Why do I need to specify Provider[...]. If all are wired why not just auto-wire IRegisteredClass interface to the object that is registered in some container that implements this interface?

I believe main reason is the fact that Python type system is different from Java-like ones. While technically you can achieve something similar to your suggestion, it falls apart when you have to deal with protocols, python generics, missing type info, etc... Python does have some notion of nominative type system to make this work, but still its dynamic nature makes it difficult to work with types in general.

I was not here since project inception, but I've tried implementing my own DI solution once. I've abandoned the idea because loads of emerging edge cases using this approach.

Is there a way to auto-wire?

So no, not now (given your definition of auto-wire).

@dbarwacz If you need full decoupling, use Provide["service"] notation (see docs). But in general, I prefer to use @inject as a last resort, when there is no other way to provide dependency into your class/function and suggest you to do so too. This keeps your code clean from DI stuff, not interfering with DI provided by test suite (pytest fixtures).

ZipFile avatar Dec 17 '24 16:12 ZipFile