Add autowiring of concrete types in existing instances

This commit is contained in:
Mike Bierlee 2014-05-27 01:54:08 +02:00
parent 7d1fe2deda
commit a9e5b315e3
2 changed files with 39 additions and 0 deletions

View file

@ -0,0 +1,16 @@
module poodinis.autowire;
public import poodinis.container;
enum Autowire;
public void autowire(Type)(Container container, Type instance) {
import std.stdio;
foreach (member ; __traits(derivedMembers, Type)) {
foreach (attribute; mixin(`__traits(getAttributes, Type.` ~ member ~ `)`) ) {
if (is(attribute : Autowire)){
__traits(getMember, instance, member) = container.resolve!(typeof(__traits(getMember, instance, member)));
}
}
}
}

View file

@ -0,0 +1,23 @@
import poodinis.autowire;
version(unittest) {
class ComponentA {
}
class ComponentB {
public @Autowire ComponentA componentA;
public bool componentIsNull() {
return componentA is null;
}
}
// Test autowiring concrete type to existing instance
unittest {
auto container = new Container();
container.register!ComponentA;
ComponentB componentB = new ComponentB();
container.autowire!(ComponentB)(componentB);
assert(!componentB.componentIsNull(), "Autowirable dependency failed to autowire");
}
}