【发布时间】:2016-01-01 06:58:11
【问题描述】:
我的 Play 应用程序 (Play 2.4.3) 中的 Slick 配置存在问题。 我阅读了documentation article,但想将 dbConfig 从控制器移动到指定的 trait 并将这个 trait 混合到存储库类中。
项目中有几个文件:ClientRepository (class), BaseClientRepository (trait) 和 BaseDbRepository (trait)。
trait BaseDbRepository {
val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
import dbConfig.driver.api._
def withConnection[T](f: => DBIOAction[T, NoStream, Nothing]) = {
dbConfig.db.run(f)
}
}
trait BaseClientRepository {
def getById(id: Int): Future[Client]
def getByLocation(location: String): Future[Seq[Client]]
}
class ClientRepository extends BaseDbRepository with BaseClientRepository {
def getById: Future[Client] = withConnection {
...
}
def getByLocation: Future[Seq[Client]] = withConnection {
...
}
}
这对我的客户端控制器很有效:
class Client extends Controller {
def getById(id: Int) = ???
}
但是当我尝试将 DI 与 Guice 一起使用时:
class Client @Inject()(clientRepository: BaseClientRepository) extends Controller {
def getById(id: Int) = Action.async {
// I try to use client repository here
}
}
它失败并出现以下异常 CreationException: 无法创建注入器,看到如下错误:
1) 捕获并报告异常。消息:没有启动的应用程序 在 com.google.inject.util.Modules$OverrideModule.configure(Modules.java:177)
我尝试将此定义 val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current) 移动到 Global.scala 中,它可以正常工作,但现在我不推荐使用 Global.scala。
那么,最好的地方在哪里?
更新:我使用注入模块进行 DI 配置:
class InjectionModule extends AbstractModule {
def configure() {
bind(classOf[BaseClientRepository]).toInstance(new ClientRepository)
}
}
【问题讨论】:
标签: scala playframework slick slick-3.0