mirror of
https://github.com/mbierlee/poodinis.git
synced 2024-11-15 04:04:01 +01:00
Add registration class that will autowire instances itself
This commit is contained in:
parent
82ea4369b8
commit
9d931f511b
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue