From 5d7a21ae52c9799d4ffc3e302e72e649da60c8b0 Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Wed, 26 Nov 2014 23:20:49 +0100 Subject: [PATCH] Add ability to register multiple concrete classes for same supertype --- source/poodinis/dependency.d | 12 +++++++----- test/poodinis/dependencytest.d | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/source/poodinis/dependency.d b/source/poodinis/dependency.d index c7568bd..6601de0 100644 --- a/source/poodinis/dependency.d +++ b/source/poodinis/dependency.d @@ -37,9 +37,9 @@ class DependencyContainer { private static DependencyContainer instance; - private Registration[TypeInfo] registrations; + private Registration[][TypeInfo] registrations; - private Registration*[] autowireStack; + private Registration[] autowireStack; public Registration register(ConcreteType)() { return register!(ConcreteType, ConcreteType)(); @@ -55,7 +55,7 @@ class DependencyContainer { Registration newRegistration = new Registration(registeredType, concreteType); newRegistration.singleInstance(); - registrations[registeredType] = newRegistration; + registrations[registeredType] ~= newRegistration; return newRegistration; } @@ -65,11 +65,13 @@ class DependencyContainer { writeln("DEBUG: Resolving type " ~ resolveType.toString()); } - Registration* registration = resolveType in registrations; - if (!registration) { + auto candidates = resolveType in registrations; + if (!candidates) { throw new ResolveException("Type not registered.", resolveType); } + auto registration = (*candidates)[0]; + RegistrationType instance = cast(RegistrationType) registration.getInstance(); if (!autowireStack.canFind(registration)) { diff --git a/test/poodinis/dependencytest.d b/test/poodinis/dependencytest.d index c253532..dd3bd6f 100644 --- a/test/poodinis/dependencytest.d +++ b/test/poodinis/dependencytest.d @@ -81,6 +81,15 @@ version(unittest) { public Banana banana; } + interface Color { + } + + class Blue : Color { + } + + class Red : Color { + } + // Test register concrete type unittest { auto container = new DependencyContainer(); @@ -257,4 +266,19 @@ version(unittest) { } assert(false); } + + // Test register multiple concrete classess to same interface type + unittest { + auto container = new DependencyContainer(); + container.register!(Color, Blue); + container.register!(Color, Red); + } + + // Test removing all registrations for type with multiple registrations. + unittest { + auto container = new DependencyContainer(); + container.register!(Color, Blue); + container.register!(Color, Red); + container.removeRegistration!Color; + } } \ No newline at end of file