[英]DI or Service Locator : Injecting implementations at run-time ( no static binding ) in scala
[英]Scala service separating by environment (service locator?)
我的Scala應用程序支持2種環境:TEST和PROD。 區別在於使用服務。 例如,生產Emailer實際上會發送一封電子郵件,而測試Emailer則是存根或模擬。 環境由參數配置。 如何實現按環境隔離的服務? 您喜歡像Guice這樣的DI解決方案嗎?
除了Guice,如果需要,您可以繼續使用本機Scala蛋糕模式依賴項注入。
// MyService.scala
trait MyService {
this: Emailer => // Cake pattern: this must be instatiated with an Emailer trait
def doSomething() {
//...
this.email(...)
//...
}
}
// Somewhere else
trait Emailer { def email(args: String): Unit }
trait MockEmailer { override def email(args: String) = println("Email was sent!") }
trait RealEmailer { override def email(args: String) = actuallySendAnEmail(args) }
// Application.scala
sealed trait Environment
case object Test extends Environment
case object Prod extends Environment
object Application {
private var _environment: Environment = Test // Choose default
def environment = _environment
def main(args: Array[String) {
// Determine environment at startup
if(args.contains("PROD") {
_environment = Prod
} else {
_environment = Test
}
// ...
}
}
// Configuration.scala
val myService = Application.environment match {
case Test => new MyService with MockEmailer
case Prod => new MyService with RealEmailer
}
自己編寫需要花費幾行,但是不需要任何單獨的依賴注入框架及其自身的注釋詳細程度。 此外,您將不會遇到運行時依賴項注入錯誤-Scala編譯器保證此方法將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.