Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compile time DI for play
package application
import akka.actor.Scheduler
import application.filters.ExampleFilter
import com.typesafe.config.Config
import controllers.HomeController
import play.api.ApplicationLoader.Context
import play.api.BuiltInComponentsFromContext
import play.api.cache.EhCacheComponents
import router.Routes
import scala.concurrent.ExecutionContext
/**
*
*/
class AppComponents(context: Context)(implicit val ec: ExecutionContext)
extends BuiltInComponentsFromContext(context)
with EhCacheComponents {
val config: Config = context.initialConfiguration.underlying
implicit val scheduler: Scheduler = actorSystem.scheduler
lazy val homeController = new HomeController()
// order matters - should be the same as routes file
lazy val router = new Routes(
httpErrorHandler,
homeController
)
val exampleFilter: ExampleFilter = new ExampleFilter()
override lazy val httpFilters = Seq(exampleFilter)
}
play.application.loader = application.AppLoader
package application
import play.api.ApplicationLoader.Context
import play.api.{Application, ApplicationLoader, LoggerConfigurator}
import scala.concurrent.ExecutionContext
class AppLoader extends ApplicationLoader {
implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext
override def load(context: Context): Application = {
LoggerConfigurator(context.environment.classLoader).foreach {
_.configure(context.environment)
}
val components: AppComponents = new AppComponents(context)
components.application
}
}
package controllers
import play.api.mvc._
import services.DummyService
import scala.concurrent.ExecutionContext
class HomeController(implicit ec: ExecutionContext) extends Controller {
def index = Action.async {
DummyService.doSomething.map(Ok(_))
}
}
@jonas-depop

This comment has been minimized.

Copy link

jonas-depop commented May 4, 2018

To be complete you might want to add the configuration in application.conf

@harrylaou

This comment has been minimized.

Copy link
Owner Author

harrylaou commented May 11, 2018

Right. Just did it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.