【问题标题】:Scala service separating by environment (service locator?)Scala 服务按环境分离(服务定位器?)
【发布时间】:2014-05-30 10:34:23
【问题描述】:

我的 Scala 应用程序支持 2 种环境:TEST 和 PROD。区别在于使用服务。例如,生产Emailer 实际上发送一封电子邮件,而测试Emailer 是存根或模拟。 环境由参数配置。 你如何实现这样一个按环境分离的服务?你喜欢像 Guice 这样的 DI 解决方案吗?

【问题讨论】:

    标签: scala dependency-injection production-environment service-locator


    【解决方案1】:

    除了 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 编译器保证这将起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2019-07-09
      • 2018-09-06
      • 2011-06-21
      相关资源
      最近更新 更多