Junichi Sakaeda Junichi Sakaeda - 3 months ago 10
Scala Question

Is there any way to use Inject directly from model or other class without controller?

I just start using playframework 2.5 scala.

The example about usage of Inject I found is only from controller.Like:

class SampController @Inject()(service:Service) extends Controller{
def index = Action{implict request =>
..
sample.exec(service)
..
}
}

class Sample{
def exec(service:Service) = {
...
}
}


But, I'd like to injected object directly from "Sample".
Is there any way?

class SampController extends Controller{
def index = Action{implict request =>
...
sample.exec()
...
}
}

class Sample{
def exec = {
val service:Service = #Any way to get injected object here?
...
}
}


Thank you.

Answer

You can do use guice dependency injection on Sample and inject Service into it, then inject Sample into controller.

@Singleton
class SampController @Inject(sample: Sample) extends Controller {
  def index = Action { implict request =>
    ...
    sample.exec()
    ...
  }
}

@Singleton
class Sample @Inject() (service: Service) {
   def exec = {
    service.doSomething()
    ...
  }
}