From a53080c109e13304591b0ed3f7a75874675080ad Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Sun, 1 Jun 2014 23:49:12 +0200 Subject: [PATCH] Prevent endless recursion on autowiring circular dependencies --- source/poodinis/container.d | 16 +++++++++++++++- test/poodinis/containertest.d | 4 ++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/source/poodinis/container.d b/source/poodinis/container.d index d146004..78f68f1 100644 --- a/source/poodinis/container.d +++ b/source/poodinis/container.d @@ -31,6 +31,8 @@ class Container { private Registration[TypeInfo] registrations; + private Registration* registrationBeingResolved; + public Registration register(ConcreteType)() { return register!(ConcreteType, ConcreteType)(); } @@ -52,8 +54,20 @@ class Container { throw new ResolveException("Type not registered.", resolveType); } + auto initialResolve = false; + if (registrationBeingResolved is null) { + registrationBeingResolved = registration; + initialResolve = true; + } + RegistrationType instance = cast(RegistrationType) registration.getInstance(); - this.autowire!(RegistrationType)(instance); + if (initialResolve || registrationBeingResolved !is registration) { + this.autowire!(RegistrationType)(instance); + } + if (initialResolve) { + registrationBeingResolved = null; + } + return instance; } diff --git a/test/poodinis/containertest.d b/test/poodinis/containertest.d index ed84fdd..0e4273d 100644 --- a/test/poodinis/containertest.d +++ b/test/poodinis/containertest.d @@ -40,7 +40,7 @@ version(unittest) { class ComponentMouse { @Autowire - public ComponentMouse cat; + public ComponentCat cat; } // Test register concrete type @@ -133,7 +133,7 @@ version(unittest) { container.register!ComponentCat; auto mouse = container.resolve!ComponentMouse; auto cat = container.resolve!ComponentCat; - assert(mouse.cat is cat && cat.mouse is mouse, "Circular dependencies should be autowirable"); + assert(mouse.cat is cat && cat.mouse is mouse && mouse !is cat, "Circular dependencies should be autowirable"); } // Test remove registration