有没有办法直接从模型或其他类没有控制器使用Inject?

时间:2016-08-29 07:55:08

标签: scala playframework dependency-injection guice

我刚开始使用playframework 2.5 scala。

关于Inject I的使用示例仅来自controller.Like:

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

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

但是,我想直接从“Sample”中注入对象。 有什么办法吗?

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?
     ...
  }
}

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在Sample上使用guice依赖注入并将Service注入其中,然后将Sample注入控制器。

@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()
    ...
  }
}