[英]How to inject a trait with macwire
I have a Scala trait 我有Scala特质
trait UserRepository {
def findByEmail(email: String): User
}
I would like to inject this into a service with MacWire 我想将其注入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 找不到accounts.repository.UserRepository的公共构造函数或伴随对象
You may try to transform userRepo
to class parameter, that allows macwire automatically provide its value for service: 您可以尝试将userRepo
转换为类参数,该参数允许macwire自动提供其用于服务的值:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.