Marcos
Marcos

Reputation: 756

How do I inject ReactiveMongoApi trait in a Repository with macwire?

I'm new to Play framework and all the Scala stack. I'm trying to implement dependency injection using macwire and ReactiveMongo to handle my MongoDB database.

I have this classes to define repositories.

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
}

Repository Implementation:

class UserRepositoryImpl(val reactiveMongoApi: ReactiveMongoApi) extends UserRepository {

  override val collectionName = "user"

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

I'm trying to wire the dependencies through 'wire' method like this:

trait RepositoryModule {

  import com.softwaremill.macwire._

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

And I have an application loader defined like this:

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]
  }
}

But I get the error:

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

Notice that I have extended ReactiveMongoApiFromContext in my ApplicationLoader.

I am also extending ReactiveMongoComponents in my repository to be able to access the reactiveMongoApi which gives me access to the database. Is that correct?

How can I wire the ReactiveMongoApi in my implementation of the repository so I can access the database and collections?

Upvotes: 1

Views: 310

Answers (0)

Related Questions