Add ability to register multiple concrete classes for same supertype

This commit is contained in:
Mike Bierlee 2014-11-26 23:20:49 +01:00
parent ae139d5f1f
commit 5d7a21ae52
2 changed files with 31 additions and 5 deletions

View file

@ -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)) {

View file

@ -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;
}
}