简体   繁体   中英

How to inject a trait with macwire

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM