1

我是 Play 框架和所有 Scala 堆栈的新手。我正在尝试使用 macwire 和 ReactiveMongo 来实现依赖注入来处理我的 MongoDB 数据库。

我有这些类来定义存储库。

trait BaseRepository extends ReactiveMongoComponents {

  /**
    * collection to retrieve documents from when accessing the database
    */
  val collectionName: String

  /**
    *
    * @return collection future instance
    */
  def collection: Future[BSONCollection] = reactiveMongoApi.database.map{
    _.collection(collectionName)
  }(dbContext)
}

用户存储库特征:

trait UserRepository extends BaseRepository {

  def findUserByUsername(username: String): User
}

存储库实现:

class UserRepositoryImpl(val reactiveMongoApi: ReactiveMongoApi) extends UserRepository {

  override val collectionName = "user"

  override def findUserByUsername(username: String): User = User("user", "password")
}

我正在尝试通过这样的“wire”方法连接依赖项:

trait RepositoryModule {

  import com.softwaremill.macwire._

  lazy val reactiveMongoApi = wire[ReactiveMongoApi]
  lazy val userDAO = wire[UserRepositoryImpl]
}

我有一个这样定义的应用程序加载器:

class MyApplicationLoader extends ApplicationLoader {
  def load(context: Context): Application = new AppComponents(context).application
}

class AppComponents(context: Context) extends ReactiveMongoApiFromContext(context)
  with AppModule
  with AssetsComponents
  with I18nComponents
  with play.filters.HttpFiltersComponents {

  // set up logger
  LoggerConfigurator(context.environment.classLoader).foreach {
    _.configure(context.environment, context.initialConfiguration, Map.empty)
  }

  lazy val router: Router = {
    // add the prefix string in local scope for the Routes constructor
    val prefix: String = "/"
    wire[Routes]
  }
}

但我得到了错误:

Cannot find a public constructor nor a companion object for [play.modules.reactivemongo.ReactiveMongoApi

请注意,我已经ReactiveMongoApiFromContext在我的ApplicationLoader.

我还在ReactiveMongoComponents我的存储库中进行扩展,以便能够访问reactiveMongoApi这使我能够访问数据库。那是对的吗?

如何在我的存储库实现中连接 ReactiveMongoApi,以便我可以访问数据库和集合?

4

0 回答 0