Prevent multiple registrations of same super- and concrete type

This commit is contained in:
Mike Bierlee 2014-11-26 23:37:12 +01:00
parent 5d7a21ae52
commit d6e3043c7d
2 changed files with 27 additions and 0 deletions

View file

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

View file

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