How to inject a trait with macwire

1.2k Views Asked by At

I have a Scala trait

trait UserRepository {
  def findByEmail(email: String): User
}

I would like to inject this into a service with MacWire

class AccountService(){
  val userRepo = wire[UserRepository]
}

And then use it in a test or class

class AccountServiceSpec {
  val userRepo = new UserRepositoryImpl()
  val accountSvc = new AccountService() //<--not manually injecting repo in service constructor
}

but I'm getting a compile error in the service class

Cannot find a public constructor nor a companion object for accounts.repository.UserRepository

1

There are 1 best solutions below

1
On BEST ANSWER

You may try to transform userRepo to class parameter, that allows macwire automatically provide its value for service:

import com.softwaremill.macwire._

case class User(email: String)

trait UserRepository {
  def findByEmail(email: String): User
}

class AccountService(val userRepo: UserRepository)

class UserRepositoryImpl extends UserRepository{
  def findByEmail(email: String): User = new User(email)
}

class AccountServiceSpec {
  val userRepo = new UserRepositoryImpl()
  val accountSvc = wire[AccountService] //<--not manually injecting repo in service constructor
}