Skip to content

Block based container initialization

Ilya Puchka edited this page Aug 19, 2016 · 2 revisions

When calling the initializer of DependencyContainer(), you can pass a configuration block that will be called right after the initialization. This allows you to have a nice syntax to do all your register calls in there, instead of having to do them separately.

It may not seem to provide much, but it gets very useful, because instead of having to setup the container like this:

let container: DependencyContainer = {
    let container = DependencyContainer()
    //register components here
    return container
    }()

you can instead write this exact equivalent code, which is more compact, and indent better in Xcode (as the final closing bracket is properly aligned):

let container = DependencyContainer { container in
    //register components here
}

Warning: When using this style of container initialization if you need to reference container inside factories that are registered in this container make sure you don't create retain cycles. You can do that by using weak/unowned reference to the container:

let container = DependencyContainer { container in
    unowned let container = container
    container.register { //it is safe now to reference container here }
}