Add registration class that will autowire instances itself

This commit is contained in:
Mike Bierlee 2015-01-25 15:07:11 +01:00
parent 82ea4369b8
commit 9d931f511b
2 changed files with 64 additions and 36 deletions

View file

@ -10,6 +10,7 @@ module poodinis.autowire;
public import poodinis.container;
import std.typetuple;
import std.exception;
debug {
import std.stdio;
@ -81,3 +82,19 @@ mixin template AutowireConstructor() {
public void globalAutowire(Type)(Type instance) {
DependencyContainer.getInstance().autowire(instance);
}
class AutowiredRegistration(RegistrationType : Object) : Registration {
private DependencyContainer container;
public this(TypeInfo registeredType, DependencyContainer container) {
enforce(!(container is null), "Argument 'container' is null. Autowired registrations need to autowire using a container.");
this.container = container;
super(registeredType, typeid(RegistrationType));
}
public override Object getInstance() {
RegistrationType instance = cast(RegistrationType) super.getInstance();
container.autowire(instance);
return instance;
}
}

View file

@ -172,4 +172,15 @@ version(unittest) {
assert(bootstrapBootstrap.componentX is componentX, "Autowiring class with multiple qualifiers failed");
assert(bootstrapBootstrap.componentC is componentC, "Autowiring class with multiple qualifiers failed");
}
// Test getting instance from autowired registration will autowire instance
unittest {
auto container = new DependencyContainer();
container.register!ComponentA;
auto registration = new AutowiredRegistration!ComponentB(typeid(ComponentB), container).singleInstance();
auto instance = cast(ComponentB) registration.getInstance();
assert(!instance.componentIsNull());
}
}