diff --git a/source/poodinis/autowire.d b/source/poodinis/autowire.d index e97ac43..d16980d 100644 --- a/source/poodinis/autowire.d +++ b/source/poodinis/autowire.d @@ -8,7 +8,7 @@ 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)){ + if (is(attribute : Autowire) && __traits(getMember, instance, member) is null){ __traits(getMember, instance, member) = container.resolve!(typeof(__traits(getMember, instance, member))); } } diff --git a/test/poodinis/autowiretest.d b/test/poodinis/autowiretest.d index db78ad4..f0cea0f 100644 --- a/test/poodinis/autowiretest.d +++ b/test/poodinis/autowiretest.d @@ -19,7 +19,7 @@ version(unittest) { } class ComponentD { - public @Autowire InterfaceA componentC; + public @Autowire InterfaceA componentC = null; public bool componentIsNull() { return componentC is null; @@ -43,4 +43,16 @@ version(unittest) { container.autowire!(ComponentD)(componentD); 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"); + } } \ No newline at end of file