简体   繁体   English

Scala服务按环境分开(服务定位器?)

[英]Scala service separating by environment (service locator?)

My Scala application supports 2 environments: TEST and PROD. 我的Scala应用程序支持2种环境:TEST和PROD。 The difference is in using services. 区别在于使用服务。 For example, production Emailer actualy sends an email, and test Emailer is rather stub or mock. 例如,生产Emailer实际上会发送一封电子邮件,而测试Emailer则是存根或模拟。 The environment is configured by parameter. 环境由参数配置。 How do you implement such a service separating by environment? 如何实现按环境隔离的服务? Do you prefer some solution with DI like Guice? 您喜欢像Guice这样的DI解决方案吗?

In addition to Guice, you can keep using the native Scala cake pattern dependency injection if you want. 除了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
}

It takes a handful of lines to write this yourself, but it doesn't require any seperate dependency injection framework with its own annotation verbosities. 自己编写需要花费几行,但是不需要任何单独的依赖注入框架及其自身的注释详细程度。 In addition, you won't encounter runtime dependency injection errors - the Scala compiler guarantees this will work. 此外,您将不会遇到运行时依赖项注入错误-Scala编译器保证此方法将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM