如何正确使用DI注入Play控制器的构造函数?

时间:2017-02-14 13:20:26

标签: scala dependency-injection playframework guice akka-remoting

我正在将Play 2.3.x应用迁移到Play 2.5.x,并且在使用依赖注入方面遇到了一些问题。

在2.3中,我有一个特征HasRemoteActor,控制器可以根据配置混合使用某个远程actor。由于这需要应用程序的配置对象,现在要求它成为一个类,以便可以注入配置。这是我的尝试:

/*
   Dummy controller that has environment and configuration manually injected.
*/
class ConfigurationController(env: play.api.Environment,
                              conf: play.api.Configuration) extends Controller {

}

/*
  Dummy controller that has environment and configuration manually injected, but 
  sets up a remote client.
*/ 
class RemoteActorController(env: play.api.Environment, conf: play.api.Configuration)
  extends ConfigurationController(env, conf) {

  protected val remoteActorName = "foo"
  private val remoteActorConf = conf.underlying.getConfig(remoteActorName)
  private val system = ActorSystem("HttpServerSystem", ConfigFactory.load())

  private val tcpInfo = remoteActorConf.getConfig("akka.remote.netty.tcp")
  private val hostname = tcpInfo.getString("hostname")
  private val port = tcpInfo.getString("port")

  val path = s"akka.tcp://PubSubMember@$hostname:$port/system/receptionist"

  private val initialContacts = Set(ActorPath.fromString(path))


  protected val client = system.actorOf(
    ClusterClient.props(ClusterClientSettings(system).withInitialContacts(
        initialContacts)),
    "ClusterClient"
  )
}

/*
   Actual controller whose actions correspond to endpoints in `conf/routes`.
*/
@Singleton
class BarController @Inject()(env: play.api.Environment,
                              conf: play.api.Configuration) extends
    RemoteActorController(env, conf) {

    // ...

}

然而,当我启动我的应用程序时,我发现actor系统始终无法找到它的端口(即使没有任何东西正在侦听该端口),无论端口号如何。

play.api.UnexpectedException: Unexpected exception[ProvisionException: Unable to provision, see the following errors:

1) Error injecting constructor, org.jboss.netty.channel.ChannelException: Failed to bind to: /127.0.0.1:8888

注射的时间似乎有问题,但我对DI很新,我在调试时遇到了麻烦。

我尝试将routesGenerator := InjectedRoutesGenerator添加到build.sbt并使用@为我注入的路由关联的控制器添加前缀,但仍然找到相同的运行时异常。

有人有建议吗?

1 个答案:

答案 0 :(得分:1)

我不会为此使用继承。相反,我会选择这样的东西(我假设你正在使用guice):

@Singleton
class RemoteActorAdapter @Inject() (env: Environment, conf: Configuration) {

  // all other initialization code
  val client: ActorRef = ???

}

在想要使用这些东西的控制器中:

class MyController @Inject() (remoteAdapterProvider: Provider[RemoteActorAdapter]) extends Controller {
  def index = Action {
    remoteAdapterProvider.get.client ! Hello
  }
}

所以诀窍在于,通过使用提供程序,您将绑定等的初始化推迟到需要的时间。

相关问题