Skip to content
Browse files

Adds support for orderly destruction of managed singletons using Inje…

…ctor#teardown()
  • Loading branch information...
1 parent e31fa2b commit 425cd95b41e687cc7af5023fc1f34050f3a4ce10 @tschneidereit committed Jun 2, 2012
Showing with 34 additions and 1 deletion.
  1. +21 −1 src/org/swiftsuspenders/injection/Injector.as
  2. +13 −0 test/org/swiftsuspenders/InjectorTests.as
View
22 src/org/swiftsuspenders/injection/Injector.as
@@ -7,7 +7,6 @@
package org.swiftsuspenders.injection
{
- import org.swiftsuspenders.*;
import avmplus.DescribeTypeJSON;
import flash.events.EventDispatcher;
@@ -385,6 +384,27 @@ package org.swiftsuspenders.injection
}
/**
+ * Destroys the injector by cleaning up all instances it manages.
+ *
+ * Cleanup in this context means iterating over all mapped dependency providers and invoking
+ * their <code>destroy</code> methods and calling preDestroy methods on all objects the
+ * injector created or injected into.
+ *
+ * Of note, the <link>SingletonProvider</link>'s implementation of <code>destroy</code>
+ * invokes all preDestroy methods on the managed singleton to guarantee its orderly
+ * destruction. Implementers of custom implementations of <link>DependencyProviders</link>
+ * are encouraged to do likewise.
+ */
+ public function teardown() : void
+ {
+ for each (var mapping : InjectionMapping in _mappings)
+ {
+ mapping.getProvider().destroy();
+ }
+ _mappings = null;
+ }
+
+ /**
* Creates a new <code>Injector</code> and sets itself as that new <code>Injector</code>'s
* <code>parentInjector</code>.
*
View
13 test/org/swiftsuspenders/InjectorTests.as
@@ -922,5 +922,18 @@ package org.swiftsuspenders
injector.destroyInstance(target);
assertThat(target, hasPropertyWithValue("preDestroyCalled", true));
}
+
+ [Test]
+ public function injectorTeardownDestroysAllSingletons() : void
+ {
+ injector.map(Clazz).asSingleton();
+ injector.map(Interface).toSingleton(Clazz);
+ const singleton1 : Clazz = injector.getInstance(Clazz);
+ const singleton2 : Clazz = injector.getInstance(Interface);
+ assertThat(singleton1, hasPropertyWithValue("preDestroyCalled", false));
+ assertThat(singleton2, hasPropertyWithValue("preDestroyCalled", false));
+ injector.teardown();
+ assertThat(singleton2, hasPropertyWithValue("preDestroyCalled", true));
+ }
}
}

0 comments on commit 425cd95

Please sign in to comment.
Something went wrong with that request. Please try again.