簡體   English   中英

如何使用Macwire注入特征

[英]How to inject a trait with macwire

我有Scala特質

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

我想將其注入MacWire服務中

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

然后在測試或課程中使用它

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

但是我在服務類中遇到了編譯錯誤

找不到accounts.repository.UserRepository的公共構造函數或伴隨對象

您可以嘗試將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM