Add resolving all registered types of a certain super type

This commit is contained in:
Mike Bierlee 2015-07-04 13:53:47 +02:00
parent c75fc78900
commit 53fb0d8116
2 changed files with 48 additions and 2 deletions

View file

@ -265,8 +265,11 @@ synchronized class DependencyContainer {
}
Registration registration = getQualifiedRegistration(resolveType, qualifierType, cast(Registration[]) *candidates);
QualifierType instance;
return resolveAutowiredInstance!QualifierType(registration);
}
private QualifierType resolveAutowiredInstance(QualifierType)(Registration registration) {
QualifierType instance;
if (!(cast(Registration[]) autowireStack).canFind(registration)) {
autowireStack ~= cast(shared(Registration)) registration;
instance = cast(QualifierType) registration.getInstance(new AutowireInstantiationContext());
@ -276,10 +279,42 @@ synchronized class DependencyContainer {
autowireContext.autowireInstance = false;
instance = cast(QualifierType) registration.getInstance(autowireContext);
}
return instance;
}
/**
* Resolve all dependencies registered to a super type.
*
* Returns:
* An array of autowired instances is returned. The order is undetermined.
*
* Examples:
* ---
* class Cat : Animal { ... }
* class Dog : Animal { ... }
*
* container.register!(Animal, Cat);
* container.register!(Animal, Dog);
*
* Animal[] animals = container.resolveAll!Animal;
* ---
*/
public RegistrationType[] resolveAll(RegistrationType)() {
RegistrationType[] instances;
TypeInfo resolveType = typeid(RegistrationType);
auto qualifiedRegistrations = resolveType in registrations;
if (!qualifiedRegistrations) {
throw new ResolveException("Type not registered.", resolveType);
}
foreach(registration ; cast(Registration[]) *qualifiedRegistrations) {
instances ~= resolveAutowiredInstance!RegistrationType(registration);
}
return instances;
}
private Registration getQualifiedRegistration(TypeInfo resolveType, TypeInfo qualifierType, Registration[] candidates) {
if (resolveType == qualifierType) {
if (candidates.length > 1) {

View file

@ -443,4 +443,15 @@ version(unittest) {
shared(DependencyContainer) container = new DependencyContainer();
assertThrown!RegistrationException(container.register!(TestClass, TestClass)(RegistrationOptions.ADD_CONCRETE_TYPE_REGISTRATION));
}
// Test resolving all registrations to an interface
unittest {
shared(DependencyContainer) container = new DependencyContainer();
container.register!(Color, Blue);
container.register!(Color, Red);
auto colors = container.resolveAll!Color;
assert(colors.length == 2, "resolveAll did not yield all instances of interface type");
}
}