Skip to content

Auto injection

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

Auto-injection lets your resolve all property dependencies of the instance resolved by container with just one call, also allowing a simpler syntax to register circular dependencies.

protocol Server {
    weak var client: Client? { get }
}

protocol Client: class {
    var server: Server? { get }
}

class ServerImp: Server {
    private let injectedClient = InjectedWeak<Client>()
    var client: Client? { return injectedClient.value }
}

class ClientImp: Client {
    private let injectedServer = Injected<Server>()
    var server: Server? { get { return injectedServer.value} }
}

container.register(.ObjectGraph) { ServerImp() as Server }
container.register(.ObjectGraph) { ClientImp() as Client }

let client = try! container.resolve() as Client

Auto-Injected properties are required by default, so if container fails to resolve one of them it will fail to resolve the whole object graph. You can make it optional providing false value for required in Injected or InjectedWeak constructor.

Auto-injection is performed as a last step in resolve process for each instance, after resolveDependencies block of corresponding definition is called.

Tip: You can use either Injected<T> and InjectedWeak<T> wrappers provided by Dip, or your own wrappers (even plain Box<T>) that conform to AutoInjectedPropertyBox protocol. This way you can minimise coupling with Dip.