diff --git a/source/poodinis/container.d b/source/poodinis/container.d index c9f61dc..64ff6e0 100644 --- a/source/poodinis/container.d +++ b/source/poodinis/container.d @@ -44,7 +44,7 @@ class Container { checkValidity!(InterfaceType)(registeredType, instantiatableType); } - Registration newRegistration = { registeredType, instantiatableType, new NullScope() }; + Registration newRegistration = { registeredType, instantiatableType, new SingleInstanceScope(instantiatableType) }; registrations[newRegistration.registeredType] = newRegistration; return newRegistration; } diff --git a/source/poodinis/registration.d b/source/poodinis/registration.d index ce14803..f4b1a58 100644 --- a/source/poodinis/registration.d +++ b/source/poodinis/registration.d @@ -10,7 +10,7 @@ struct Registration { throw new NoScopeDefinedException(registeredType); } - return instantiatableType.create(); + return registationScope.getInstance(); } } @@ -29,3 +29,20 @@ class NullScope : RegistrationScope { return null; } } + +class SingleInstanceScope : RegistrationScope { + TypeInfo_Class instantiatableType = null; + Object instance = null; + + this(TypeInfo_Class instantiatableType) { + this.instantiatableType = instantiatableType; + } + + public Object getInstance() { + if (instance is null) { + instance = instantiatableType.create(); + } + + return instance; + } +} diff --git a/test/poodinis/registrationtest.d b/test/poodinis/registrationtest.d index 2ef5e69..54b10cf 100644 --- a/test/poodinis/registrationtest.d +++ b/test/poodinis/registrationtest.d @@ -12,4 +12,14 @@ version(unittest) { registration.registeredType = typeid(TestType); assertThrown!(NoScopeDefinedException)(registration.getInstance()); } + + // Test getting instance from single instance scope + unittest { + Registration registration = Registration(); + registration.registeredType = typeid(TestType); + registration.registationScope = new SingleInstanceScope(typeid(TestType)); + auto instance1 = registration.getInstance(); + auto instance2 = registration.getInstance(); + assert(instance1 is instance2, "Registration with single instance scope did not return the same instance"); + } } \ No newline at end of file