-
Notifications
You must be signed in to change notification settings - Fork 72
Auto injection
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(.Shared) { ServerImp() as Server }
container.register(.Shared) { 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
parameter 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>
andInjectedWeak<T>
wrappers provided by Dip, or your own wrappers (even plainBox<T>
) that conform toAutoInjectedPropertyBox
protocol. This way you can minimise coupling with Dip.