You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.5 KiB

4 years ago
  1. import javax.inject.{Inject, Provider, Singleton}
  2. import com.example.user.UserDAO
  3. import com.example.user.slick.SlickUserDAO
  4. import com.google.inject.AbstractModule
  5. import com.typesafe.config.Config
  6. import play.api.inject.ApplicationLifecycle
  7. import play.api.{Configuration, Environment}
  8. import slick.jdbc.JdbcBackend.Database
  9. import scala.concurrent.Future
  10. import com.example.user.CarDAO
  11. import com.example.Car.slick.SlickCarDAO
  12. import com.example.services.LibraryService
  13. import com.example.user.slick.services.SlickLibraryService
  14. /**
  15. * This module handles the bindings for the API to the Slick implementation.
  16. *
  17. * https://www.playframework.com/documentation/latest/ScalaDependencyInjection#Programmatic-bindings
  18. */
  19. class Module(environment: Environment, configuration: Configuration)
  20. extends AbstractModule {
  21. override def configure(): Unit = {
  22. bind(classOf[Database]).toProvider(classOf[DatabaseProvider])
  23. bind(classOf[UserDAO]).to(classOf[SlickUserDAO])
  24. bind(classOf[CarDAO]).to(classOf[SlickCarDAO])
  25. bind(classOf[LibraryService]).to(classOf[SlickLibraryService])
  26. bind(classOf[DBCloseHook]).asEagerSingleton()
  27. }
  28. }
  29. @Singleton
  30. class DatabaseProvider @Inject() (config: Config) extends Provider[Database] {
  31. lazy val get = Database.forConfig("myapp.database", config)
  32. }
  33. /** Closes database connections safely. Important on dev restart. */
  34. class DBCloseHook @Inject() (db: Database, lifecycle: ApplicationLifecycle) {
  35. lifecycle.addStopHook { () => Future.successful(db.close()) }
  36. }