Skip to content

Auto wiring

Ilya Puchka edited this page Apr 18, 2016 · 5 revisions

When you use constructor injection to inject dependencies auto-wiring enables you to resolve it just with one call to resolve method without carying about how to resolve all constructor arguments - container will resolve them for you.

class PresenterImp: Presenter {
    init(view: ViewOutput, interactor: Interactor, router: Router) { ... }
    ...
}

container.register { RouterImp() as Router }
container.register { View() as ViewOutput }
container.register { InteractorImp() as Interactor }
container.register { PresenterImp(view: $0, interactor: $1, router: $2) as Presenter }

let presenter = try! container.resolve() as Presenter

Auto-wiring uses Swift Type Inference to infer types of constructor arguments and if they all are registered in container, they will be automatically resolved.

At the same time you are able to resolve presenter using runtime arguments:

let view = try! container.resolve() as ViewOutput
let interactor = try! container.resolve() as Interactor
let router = try! container.resolve() as Router

//without auto-wiring
let presenter = try! container.resolve(withArguments: view, interactor, router) as Presenter

Auto-wiring saves all these calls to resolve each constructor argument.