我一直在关注这篇文章,它描述了如何通过 Cake Pattern 在 Scala 中实现依赖注入:http: //jonasboner.com/real-world-scala-dependency-injection-di/
我对 Scala 有点陌生,我承认其中一些超出了我的想象,到目前为止,我已经完成了以下工作:
// Setup the component and interface
trait AccountRepositoryComponent {
val accountRepository: AccountRepositoryInterface
trait AccountRepositoryInterface {
def message: String
}
}
// An implementation
trait MyAccountRepositoryComponent extends AccountRepositoryComponent {
object AccountRepository extends AccountRepositoryInterface {
def message: String = "Hello"
}
}
// Object to configure which implementations to use and retrieve them
object ComponentRegistry extends MyAccountRepositoryComponent {
val accountRepository = AccountRepository
}
// Example service using the above
object AccountService {
val repo = ComponentRegistry.accountRepository
def say: String = repo.message
}
println(AccountService.say)
我不明白的是我现在如何将假存储库传递给帐户服务,比如将输出更改为“测试”而不是“你好”?