How to get compile time dependency injection working in Play 2.4

I found a couple of articles about this, but none of them worked for me or they missed something important. So I’m going to outline what I did in order to get this to work so that it may help future me or some other developer experiencing the same problem.

 

Create an ApplicationLoader sub class that overrides the load function.

class GrimeyAppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new GrimeyAppComponents(context).application
}

You will then need to implement the components class that the load function will create your application from.

class GrimeyAppComponents(context: Context) extends BuiltInComponentsFromContext(context) with I18nSupport {
  lazy val dbConfig: DatabaseConfig[MySQLDriver] = DatabaseConfig.forConfig("slick.dbs.default")
  lazy val db: JdbcBackend#DatabaseDef = dbConfig.db
  lazy val staticPageService = new StaticPageService(db)

  lazy val staticPageController = new StaticPageController(staticPageService, messagesApi())
  lazy val assetsController = new Assets(httpErrorHandler)

  override def router: Router = new Routes(httpErrorHandler, staticPageController,
    assetsController)

  override def messagesApi(): MessagesApi = new DefaultMessagesApi(environment, configuration, new DefaultLangs(configuration))
}

Finally, you’ll need to reference the application loader class you implemented in your application.conf. Note: This has to be the fully qualified name of the class.

play.application.loader="com.grimey.GrimeyAppLoader"