From d6e3043c7d6fc82b36c293d285829568f33222bb Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Wed, 26 Nov 2014 23:37:12 +0100 Subject: [PATCH] Prevent multiple registrations of same super- and concrete type --- source/poodinis/dependency.d | 18 ++++++++++++++++++ test/poodinis/dependencytest.d | 9 +++++++++ 2 files changed, 27 insertions(+) diff --git a/source/poodinis/dependency.d b/source/poodinis/dependency.d index 6601de0..3675fb1 100644 --- a/source/poodinis/dependency.d +++ b/source/poodinis/dependency.d @@ -53,12 +53,30 @@ class DependencyContainer { writeln(format("DEBUG: Register type %s (as %s)", concreteType.toString(), registeredType.toString())); } + auto existingRegistration = getRegistration(registeredType, concreteType); + if (existingRegistration) { + return existingRegistration; + } + Registration newRegistration = new Registration(registeredType, concreteType); newRegistration.singleInstance(); registrations[registeredType] ~= newRegistration; return newRegistration; } + private Registration getRegistration(TypeInfo registeredType, TypeInfo_Class concreteType) { + auto existingCandidates = registeredType in registrations; + if (existingCandidates) { + foreach(existingRegistration ; *existingCandidates) { + if (existingRegistration.instantiatableType == concreteType) { + return existingRegistration; + } + } + } + + return null; + } + public RegistrationType resolve(RegistrationType)() { TypeInfo resolveType = typeid(RegistrationType); debug { diff --git a/test/poodinis/dependencytest.d b/test/poodinis/dependencytest.d index dd3bd6f..8e43a58 100644 --- a/test/poodinis/dependencytest.d +++ b/test/poodinis/dependencytest.d @@ -281,4 +281,13 @@ version(unittest) { container.register!(Color, Red); container.removeRegistration!Color; } + + // Test registering same registration again + unittest { + auto container = new DependencyContainer(); + auto firstRegistration = container.register!(Color, Blue); + auto secondRegistration = container.register!(Color, Blue); + + assert(firstRegistration is secondRegistration, "First registration is not the same as the second of equal types"); + } } \ No newline at end of file