diff --git a/example/postconstructorpredestructor/app.d b/example/postconstructorpredestructor/app.d index f72f3dc..fb7c963 100644 --- a/example/postconstructorpredestructor/app.d +++ b/example/postconstructorpredestructor/app.d @@ -42,8 +42,14 @@ class AClass { public void main() { auto container = new shared DependencyContainer(); - container.register!ADependency; - container.register!AClass; + container.register!(ADependency).onConstructed((Object obj) { + writeln("ADependency constructed"); + }); + + container.register!(AClass).onConstructed((Object obj) { + writeln("AClass constructed"); + }); + auto instance = container.resolve!AClass; // Will cause the post constructor to be called. container.removeRegistration!AClass; // Will cause the pre destructor to be called. diff --git a/source/poodinis/factory.d b/source/poodinis/factory.d index aae3f52..5d80d5b 100644 --- a/source/poodinis/factory.d +++ b/source/poodinis/factory.d @@ -22,6 +22,7 @@ import std.stdio; alias CreatesSingleton = Flag!"CreatesSingleton"; alias InstanceFactoryMethod = Object delegate(); +alias InstanceEventHandler = void delegate(Object instance); class InstanceCreationException : Exception { this(string message, string file = __FILE__, size_t line = __LINE__) { @@ -39,6 +40,7 @@ struct InstanceFactoryParameters { class InstanceFactory { private Object instance = null; private InstanceFactoryParameters _factoryParameters; + private InstanceEventHandler _constructionHandler; this() { factoryParameters = InstanceFactoryParameters(); @@ -75,9 +77,17 @@ class InstanceFactory { } instance = _factoryParameters.factoryMethod(); + if(_constructionHandler !is null) { + _constructionHandler(instance); + } + return instance; } + void onConstructed(InstanceEventHandler handler) { + _constructionHandler = handler; + } + private void printDebugUseExistingInstance() { if (_factoryParameters.instanceType !is null) { writeln(format("DEBUG: Existing instance returned of type %s", _factoryParameters.instanceType.toString())); diff --git a/source/poodinis/registration.d b/source/poodinis/registration.d index cfaca3b..1a4970b 100644 --- a/source/poodinis/registration.d +++ b/source/poodinis/registration.d @@ -60,7 +60,6 @@ class Registration { return linkedRegistration.getInstance(context); } - if (instanceFactory is null) { throw new InstanceCreationException("No instance factory defined for registration of type " ~ registeredType.toString()); } @@ -72,6 +71,12 @@ class Registration { this.linkedRegistration = registration; return this; } + + Registration onConstructed(InstanceEventHandler handler) { + if(instanceFactory !is null) + instanceFactory.onConstructed(handler); + return this; + } } /**