2
votes

When defining Scala controller it to mark a class as singleton use the @Singleton annotation :

@Singleton
class Application

https://docs.oracle.com/javaee/7/api/javax/inject/Singleton.html defines singleton as 'Identifies a type that the injector only instantiates once. Not inherited.' so is Scala play dependency injection framework relying on Java dependency injection ?

From https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection 'Play supports both runtime dependency injection based on JSR 330 (described in this page) and compile time dependency injection in Scala.' Is using @Singleton utilizing 'dependency injection based on JSR 330' so to use 'compile time dependency injection in Scala' what is required ?

2

2 Answers

4
votes

is Scala play dependency injection framework relying on Java dependency injection ?

Yes,So You need to write import javax.inject._ everyfile you use DI.

What you need to do basically is

・ Define interface as trait

trait FooService {
  def getBar(baz: String):Future[Bar]
}

・ Implement the interface

class FooServiceImpl extends FooService {
  def getBar(baz: String) = ???
}

・ Bind them via Module.scala(guice style)

class Module extends AbstractModule {
  override def configure() = {
    bind(classOf[FooService]).to(classOf[FooServiceImpl])
  }
}

・Use it

class FooController @Inject()(fooService: FooService)(implicit exec: ExecutionContext) extends Controller {
  def index = Action.async = {
    fooService.getBar("fooBar").map{_.doWhatEverYouWant}
    .....
  }
}

As You can see, You need to define class parameters when you use this way of DI.This is the reason why You cannot use Scala object and use @Singleton instead.

0
votes

The main difference between compiletime and runtime DI is that with runtime DI you won't know if your dependencies will be wired and fulfilled until you run your application (i.e. you will get a runtime error instead of compile time error)

For more infos on play's compile time DI support, I highly suggest that you look into the official documentation about it.