mirror of
https://github.com/mbierlee/poodinis.git
synced 2024-11-15 04:04:01 +01:00
Add autowiring of concrete types in existing instances
This commit is contained in:
parent
7d1fe2deda
commit
a9e5b315e3
16
source/poodinis/autowire.d
Normal file
16
source/poodinis/autowire.d
Normal 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)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
23
test/poodinis/autowiretest.d
Normal file
23
test/poodinis/autowiretest.d
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue