简体   繁体   中英

Injecting service to an actor in Play 2.4 on startup

I'm currently migrating to Play 2.4 and have a problem with injecting an actor with a service.

I've moved actor creation from GlobalSettings.onStart to a module.

Module:

class MailerModule extends AbstractModule with AkkaGuiceSupport {
  override def configure() = {
    bindActor[Mailer]("mailer")
  }
}

Actor:

class Mailer @Inject() (service: MailService) extends Actor {
...
}

Now when I start the application I gen error: Error injecting constructor, java.lang.RuntimeException: There is no started application at services.MailService.<init>(MailService.scala:14)

However, if I add Logger to the actor class

class Mailer @Inject() (service: MailService) extends Actor {
  Logger.info("Starting Mailer...")
  ...
}

there's no error. I don't know why it behaves like that. It doesn't look like a good solution. Are the any others?

EDIT: It doesn't work. Looks like it's non-deterministic. How should I initialize it?

A possible problem is in the mailer itself. It is the one that is throwing the exception. It has some kind of dependency on the application itself, and sometimes the application is already started before the service's initialization logic kicks in, and sometimes it is not. Maybe you have some more refactoring to do with the service, and inject something into it also, or in any way delay its execution. Maybe you can add the code from the mail service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM