diff --git a/source/poodinis/registration.d b/source/poodinis/registration.d index 5b8915e..7759b02 100644 --- a/source/poodinis/registration.d +++ b/source/poodinis/registration.d @@ -67,16 +67,19 @@ class Registration { } alias CreatesSingleton = Flag!"CreatesSingleton"; +alias InstanceFactoryMethod = Object delegate(); class InstanceFactory { private TypeInfo_Class instanceType = null; private Object instance = null; private CreatesSingleton createsSingleton; + private InstanceFactoryMethod factoryMethod; - this(TypeInfo_Class instanceType, CreatesSingleton createsSingleton = CreatesSingleton.yes, Object existingInstance = null) { + this(TypeInfo_Class instanceType, CreatesSingleton createsSingleton = CreatesSingleton.yes, Object existingInstance = null, InstanceFactoryMethod factoryMethod = null) { this.instanceType = instanceType; this.createsSingleton = existingInstance !is null ? CreatesSingleton.yes : createsSingleton; this.instance = existingInstance; + this.factoryMethod = factoryMethod !is null ? factoryMethod : &this.createInstance; } public Object getInstance() { @@ -88,14 +91,18 @@ class InstanceFactory { return instance; } - enforce!InstanceCreationException(instanceType, "Instance type is not defined, cannot create instance without knowing its type."); debug(poodinisVerbose) { writeln(format("DEBUG: Creating new instance of type %s", instanceType.toString())); } - instance = instanceType.create(); + instance = factoryMethod(); return instance; } + + private Object createInstance() { + enforce!InstanceCreationException(instanceType, "Instance type is not defined, cannot create instance without knowing its type."); + return instanceType.create(); + } } /** diff --git a/test/poodinis/registrationtest.d b/test/poodinis/registrationtest.d index bd701a0..1fcd2f3 100644 --- a/test/poodinis/registrationtest.d +++ b/test/poodinis/registrationtest.d @@ -14,7 +14,9 @@ version(unittest) { interface TestInterface {} - class TestImplementation : TestInterface {} + class TestImplementation : TestInterface { + public string someContent = ""; + } // Test getting instance without scope defined throws exception unittest { @@ -103,4 +105,19 @@ version(unittest) { assert(instance is existingInstance, "Created factory instance is not the existing instance"); } + // Test creating instance using custom factory method + unittest { + Object factoryMethod() { + auto instance = new TestImplementation(); + instance.someContent = "Ducks!"; + return instance; + } + + auto factory = new InstanceFactory(null, CreatesSingleton.yes, null, &factoryMethod); + auto instance = cast(TestImplementation) factory.getInstance(); + + assert(instance !is null, "No instance was created by factory or could not be cast to expected type"); + assert(instance.someContent == "Ducks!"); + } + }