Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Last active October 16, 2015 14:37
Show Gist options
  • Save mathieuancelin/3efe5826a558c4507fbb to your computer and use it in GitHub Desktop.
Save mathieuancelin/3efe5826a558c4507fbb to your computer and use it in GitHub Desktop.
Compile time dependency injection in Play 2.4 (based on https://www.playframework.com/documentation/2.4.x/ScalaCompileTimeDependencyInjection)
application.secret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
application.langs="en"
logger.root=ERROR
logger.play=INFO
logger.application=DEBUG
play.application.loader=BootstrapLoader # root object of the injection tree
package controllers
import env.Env
import play.api.libs.json.JsArray
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits._
// here's where the injection takes place
class Application(env: Env) extends Controller {
import env._ // to avoid writing something like env.WS.url() or env.configuration.get...
def index = Action.async {
val url = configuration.getString("docs.url").getOrElse("http://foo.bar/stuff.json")
WS.url(url).get().map(_.json \ "docs").map(Ok(_))
}
}
import akka.actor.ActorSystem
import play.api.ApplicationLoader.Context
import play.api.cache.{CacheApi, EhCacheComponents}
import play.api.inject.Injector
import play.api.libs.concurrent.AkkaComponents
import play.api.libs.ws.WSAPI
import play.api.libs.ws.ning.NingWSComponents
import play.api.{Application, ApplicationLoader, BuiltInComponentsFromContext, Configuration}
class BootstrapLoader extends ApplicationLoader {
def load(context: Context): Application = {
// Bootstrap the injected application
new env.ApplicationEnv(context).application
}
}
package object env {
// Environment that contains useful services
class Env(val application: Application, val configuration: Configuration, val WS: WSAPI, val Akka: ActorSystem, val Cache: CacheApi, val injector: Injector)
class ApplicationEnv(context: Context)
extends BuiltInComponentsFromContext(context)
with NingWSComponents
with EhCacheComponents
with AkkaComponents {
lazy val env = new Env(application, configuration, wsApi, actorSystem, defaultCacheApi, injector)
// an injected instance of the application controller
lazy val applicationController = new controllers.Application(env)
lazy val assets = new controllers.Assets(httpErrorHandler)
// routes using injected controllers
lazy val routes = new Routes(httpErrorHandler, applicationController, assets)
}
}
name := """di-test"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
jdbc,
anorm,
cache,
ws
)
routesGenerator := InjectedRoutesGenerator // doesn't work with 2.4.0-M1, need to build 2.4-SNAPSHOT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment