diff --git a/injector.py b/injector.py index f60ef43..b159705 100644 --- a/injector.py +++ b/injector.py @@ -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. diff --git a/injector_test.py b/injector_test.py index 053c188..07de378 100644 --- a/injector_test.py +++ b/injector_test.py @@ -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'