diff --git a/source/poodinis/container.d b/source/poodinis/container.d index 1a9f2dd..cd7a14a 100644 --- a/source/poodinis/container.d +++ b/source/poodinis/container.d @@ -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) { diff --git a/test/poodinis/containertest.d b/test/poodinis/containertest.d index bbf096a..ad4e98f 100644 --- a/test/poodinis/containertest.d +++ b/test/poodinis/containertest.d @@ -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"); + } }