From 4f2f0fbe59042f500ed4bcce2a8c559032efbb7f Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Tue, 20 May 2014 22:03:50 +0200 Subject: [PATCH] Add single instance scope, make it the default scope of new registrations --- source/poodinis/container.d | 2 +- source/poodinis/registration.d | 19 ++++++++++++++++++- test/poodinis/registrationtest.d | 10 ++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) 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