ivankorobkov / python-inject

Python dependency injection
Apache License 2.0
694 stars 79 forks source link

Inject dependency to class that will be injected #53

Closed saber-solooki closed 4 years ago

saber-solooki commented 4 years ago

Suppose I have class A like this: class A: @inject.autoparams('instance_b'): def __init__(self, instance_b: B): self.instance_b= instance_b

in my configuration method: def di_configuration(binder): binder.bind(B, B()) binder.bind(A, A())

inject.configure(di_configuration)

I expect this work because A need B and I config B to be injected. but when I run my django application I get this error: inject.InjectorException: No injector is configured

ivankorobkov commented 4 years ago

Hi!

The exception is correct. You try to instantiate classes before the injector is configured:

binder.bind(B, B())
binder.bind(A, A())

You call B() and A() inside the injector configuration. @inject.autoparams try to inject dependencies into them but cannot find an injector which is not configured yet.

You need to bind classes to constructors (any callable) instead:

binder.bind(B, B)
binder.bind(A, A)

But in this particular case you can delete all explicit bindings all together:

class B:
  pass

class A:
  @inject.autoparams()
  def __init__(self, b: B):
    self.b = b

def config(binder):
  pass

inject.configure(config)
a = A()
print(a.b) # B is instantiated as a singleton and injected automatically.

See runtime bindings in readme https://github.com/ivankorobkov/python-inject#binding-types