From a9e5b315e31e9d6b68d29cfdbd31507800043908 Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Tue, 27 May 2014 01:54:08 +0200 Subject: [PATCH] Add autowiring of concrete types in existing instances --- source/poodinis/autowire.d | 16 ++++++++++++++++ test/poodinis/autowiretest.d | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 source/poodinis/autowire.d create mode 100644 test/poodinis/autowiretest.d diff --git a/source/poodinis/autowire.d b/source/poodinis/autowire.d new file mode 100644 index 0000000..e97ac43 --- /dev/null +++ b/source/poodinis/autowire.d @@ -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))); + } + } + } +} \ No newline at end of file diff --git a/test/poodinis/autowiretest.d b/test/poodinis/autowiretest.d new file mode 100644 index 0000000..59b444a --- /dev/null +++ b/test/poodinis/autowiretest.d @@ -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"); + } +} \ No newline at end of file