Skip to content

Instantly share code, notes, and snippets.

@artemnovichkov
Last active May 4, 2018 07:17
Show Gist options
  • Save artemnovichkov/ac281217059300c4a2bdd071b73c3723 to your computer and use it in GitHub Desktop.
Save artemnovichkov/ac281217059300c4a2bdd071b73c3723 to your computer and use it in GitHub Desktop.
Using protocol composition and generics for dependency injection in Interactors (VIPER, SOA, another cool keywords...)
//Inspired by: http://merowing.info/2017/04/using-protocol-compositon-for-dependency-injection/
//Protocols for objects owning services. Interactors in VIPER, for example.
protocol HasLogService {
var logService: LogService { get }
}
protocol HasLoginService {
var loginService: LoginService { get }
}
//Implementation of services
final class LogService {
func log() {
print("LogService works!")
}
}
final class LoginService {
func login() {
print("LoginService works!")
}
}
//Class that handles all services
final class InteractorDependencies: HasLogService, HasLoginService {
lazy var logService: LogService = .init()
lazy var loginService: LoginService = .init()
}
//-----------------------------------------------------------------------------------
//Example of interactor
final class Interactor {
typealias Dependencies = HasLogService
let dependencies: Dependencies
init(dependencies: Dependencies) {
self.dependencies = dependencies
}
}
let interactor = Interactor(dependencies: InteractorDependencies())
//prints "LogService works!"
interactor.dependencies.logService.log()
//Build error, because the interactor knows nothing about loginService
//interactor.dependencies.loginService.login()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment