Inject dependencies into modules when installing

This commit is contained in:
Jakub Stasiak 2013-06-29 00:26:53 +01:00
parent 39b1fa18fb
commit 7e2c5ef69a
2 changed files with 33 additions and 8 deletions

View File

@ -292,10 +292,9 @@ class Binder(object):
:param module: A Module instance, Module subclass, or a function.
"""
if isinstance(module, Module):
module(self)
elif type(module) is type and issubclass(module, Module):
module()(self)
if type(module) is type and issubclass(module, Module):
instance = self.injector.create_object(module)
instance(self)
else:
bindings = getattr(module, '__bindings__', {})
kwargs = self.injector.args_to_inject(module, bindings, module)
@ -525,10 +524,7 @@ class Injector(object):
self.binder.bind(Binder, to=self.binder)
# Initialise modules
for module in modules:
if isinstance(module, type):
module = module()
module(self.binder)
self.binder.install(module)
def get(self, interface, annotation=None, scope=None):
"""Get an instance of the given interface.

View File

@ -383,6 +383,35 @@ def test_module_provides():
assert (injector.get(str, annotation='name') == 'Bob')
def test_can_inject_into_modules():
counter = [0]
class M(Module):
@inject(f=float)
def __init__(self, f):
counter[0] += 1
assert (f == 0.0)
@inject(s=str)
def configure(self, binder, s):
counter[0] += 1
assert (s == '')
Injector(M)
assert (counter[0] == 2)
Injector(M(f=0.0))
assert (counter[0] == 4)
@inject(i=int)
def configure(binder, i):
counter[0] += 1
assert (i == 0)
Injector(configure)
assert (counter[0] == 5)
def test_module_class_gets_instantiated():
name = 'Meg'