Only autowire members which are null

This commit is contained in:
Mike Bierlee 2014-05-30 00:33:08 +02:00
parent 4957b67b49
commit 35acaa84d1
2 changed files with 14 additions and 2 deletions

View file

@ -8,7 +8,7 @@ public void autowire(Type)(Container container, Type instance) {
import std.stdio; import std.stdio;
foreach (member ; __traits(derivedMembers, Type)) { foreach (member ; __traits(derivedMembers, Type)) {
foreach (attribute; mixin(`__traits(getAttributes, Type.` ~ member ~ `)`) ) { foreach (attribute; mixin(`__traits(getAttributes, Type.` ~ member ~ `)`) ) {
if (is(attribute : Autowire)){ if (is(attribute : Autowire) && __traits(getMember, instance, member) is null){
__traits(getMember, instance, member) = container.resolve!(typeof(__traits(getMember, instance, member))); __traits(getMember, instance, member) = container.resolve!(typeof(__traits(getMember, instance, member)));
} }
} }

View file

@ -19,7 +19,7 @@ version(unittest) {
} }
class ComponentD { class ComponentD {
public @Autowire InterfaceA componentC; public @Autowire InterfaceA componentC = null;
public bool componentIsNull() { public bool componentIsNull() {
return componentC is null; return componentC is null;
@ -43,4 +43,16 @@ version(unittest) {
container.autowire!(ComponentD)(componentD); container.autowire!(ComponentD)(componentD);
assert(!componentD.componentIsNull(), "Autowirable dependency failed to autowire"); assert(!componentD.componentIsNull(), "Autowirable dependency failed to autowire");
} }
// Test autowiring will only happen once
unittest {
auto container = new Container();
container.register!(InterfaceA, ComponentC).newInstance();
ComponentD componentD = new ComponentD();
container.autowire!(ComponentD)(componentD);
auto expectedComponent = componentD.componentC;
container.autowire!(ComponentD)(componentD);
auto actualComponent = componentD.componentC;
assert(expectedComponent is actualComponent, "Autowiring the second time wired a different instance");
}
} }