Last active
December 29, 2016 11:08
-
-
Save gbersac/21ba13473f66ccaa7819fc402fac0232 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from : http://jonasboner.com/real-world-scala-dependency-injection-di/ | |
case class User(name: String) | |
trait UserRepositoryComponent { | |
val userRepository: UserRepository | |
trait UserRepository { | |
def authenticate(username: String, password: String): User | |
def create(user: User): Unit | |
def delete(user: User): Unit | |
} | |
} | |
trait UserServiceComponent { this: UserRepositoryComponent => | |
val userService: UserService | |
class UserService { | |
def authenticate(username: String, password: String): User = userRepository.authenticate(username, password) | |
def create(username: String) = userRepository.create(new User(username)) | |
def delete(user: User) = userRepository.delete(user) | |
} | |
} | |
object ComponentRegistry extends UserServiceComponent with UserRepositoryComponent { | |
val userRepository = new UserRepository { // this is where dependency injection happens | |
def authenticate(username: String, password: String): User = { | |
println("authenticating user: " + username) | |
User(username) | |
} | |
def create(user: User) = println("creating user: " + user) | |
def delete(user: User) = println("deleting user: " + user) | |
} | |
val userService = new UserService | |
} | |
val userService = ComponentRegistry.userService | |
userService.authenticate("me", "xxxx") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment