Swinject: Resolving using a list of metatypes

Created on 4 Jul 2017  路  2Comments  路  Source: Swinject/Swinject

Not sure if this is an issue with Swinject, but I've opened this question on SO:

https://stackoverflow.com/questions/44895006/swinject-resolving-using-a-list-of-types

question

All 2 comments

Hello,
the problem is that you can't use protocol and class types interchangingly. The Task.self doesn't produce Task.Type but Task.Protocol.

I would suggest that passing around metatypes in your application is not the best idea. What about using a factory pattern with something like this?

protocol Task: class { }

class ConcreteTaskA: Task {}
class ConcreteTaskB: Task {}

typealias TaskFactory = (Resolver)->Task

func getTypeFactories() -> [TaskFactory] {
    return [{ r in r.resolve(ConcreteTaskA.self)! }, { r in r.resolve(ConcreteTaskB.self)! }]
}
func test() {
    var concreteTasks = [Task]()
    for typeFactory in getTypeFactories() {
        let container = Container()
        let task = typeFactory(container)
        concreteTasks.append(task)
    }
}

Ah that's interesting. Thanks for that solution, hadn't thought of that!

Was this page helpful?
0 / 5 - 0 ratings