我是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)
}
UserRepository Trait:
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,以便我可以访问数据库和集合?