[2]
Goal: Have tests
https://devopedia.org/dependency-injection
import com.google.inject.Guice
object DateApp extends App {
val injector = Guice.createInjector()
val date = injector.getInstance(
classOf[java.util.Date]
)
println(date.toString)
}
[info] Running DateApp DateApp
Fri Dec 07 18:09:06 GMT 2018
trait FizzBuzz {
def fizzbuzz(number: Int): String
}
object AbstractApp extends App {
val injector = Guice.createInjector()
val fizzbuzz = injector.getInstance(
classOf[FizzBuzz]
)
println(fizzbuzz.fizzbuzz(15))
}
[error] (run-main-1) com.google.inject.ConfigurationException: Guice configuration errors:
[error]
[error] 1) No implementation for FizzBuzz was bound.
[error] while locating FizzBuzz
[error]
[error] 1 error
[error] com.google.inject.ConfigurationException: Guice configuration errors:
[error]
[error] 1) No implementation for FizzBuzz was bound.
[error] while locating FizzBuzz
[error]
[error] 1 error
object ModuleApp extends App {
val injector = Guice.createInjector(
FizzBazzModule
)
val fizzbazz = injector.getInstance(
classOf[FizzBazz]
)
println(fizzbazz.fizzbazz(15))
}
object FizzBazzModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[FizzBazz])
.to(classOf[DefaultFizzBazz])
}
}
class DefaultFizzBuzz extends FizzBuzz {
def fizzbuzz(number: Int): String = {
(number % 3, number % 5) match {
case (0, 0) => "fizzbuzz"
case (0, _) => "fizz"
case (_, 0) => "buzz"
case (_, _) => number.toString
}
}
}
[info] Running ModuleApp
fizzbazz
class ConstructorService
@Inject()(implicit ec: ExecitionContext){
// Some important methods
}
class SimpleModule extends AbstractModule {
@Provider
@Singleton
def utf8: Charset = {
Charset.forName("uft-8")
}
def configure(): Unit = {
//EMPTY
}
}
configuration.getOptional[Configuration](
s"$rootServices.$serviceName"
).orElse(
configuration.getOptional[Configuration](
s"$services.$serviceName"
)
).getOrElse(???)
class ActorProvider
@Inject()(system: ActorSystem)
extends Provider[ActorRef] {
val ref = system.actorOf(Props[SomeAcotr])
override def get(): ActorRef = ref
}
class ConnectionExample
@Inject()(pool: Provider[Connection]){
def foo() = {
val connection = pool.get()
try {
// LOGIC here
} finally {
connection.close()
}
}
}
[1] https://en.wikipedia.org/wiki/SOLID
[2] http://wiki.c2.com/?HollywoodPrinciple
[3] https://www.youtube.com/watch?v=hBVJbzAagfs
[4] https://github.com/google/guice/wiki/Motivation
[5]https://www.playframework.com/documentation/2.6.x/ScalaDependencyInjection