Macwire,wireWith和隐含参数

时间:2018-02-07 06:44:10

标签: scala dependency-injection macwire

wireWith似乎在解决隐式参数方面存在一些问题。

最小例子:

import com.softwaremill.macwire._

object A {
  def props(x: Int)(implicit y: String): A = new A(x)
}

class A(x: Int)(implicit y: String) {
   val sum: String = s"$x + $y"
}

object App {
   def main(): Unit = {
     val xVal: Int = 3
     implicit val yVal: String = "5"

     // val aInstance = wire[A] // works
     // val aInstance = A.props(xVal) // works
     val aInstance: A = wireWith(A.props _) // compile error

     println(aInstance.sum)
  }
}

App.main()

错误:

Error:(21, 33) type mismatch; found   : Int required: String
    val aInstance: A = wireWith(A.props _)
                           ^

如果在implicit省略yVal,则会抱怨错误隐含:

Error:(18, 36) could not find implicit value for parameter y: String 
    val aInstance: A = wireWith(A.props _) // compile error
                              ^

这是一个简化的例子 - 在我的生产代码中我尝试连接Actor道具:

object Actor {
    def props
        (dependency: Dependency, refreshInterval: FiniteDuration @@ CacheRefreshInterval)
        (implicit ec: ExecutionContext): Props =
            Props(new Actor(dependency, refreshInterval))
}

// DI container
protected implicit def executionContext: ExecutionContext
protected lazy val dependency: Dependency = wire[Dependency]
protected lazy val refreshInterval = 2.second.taggedWith[CacheRefreshInterval]
protected lazy val actorProps: Props @@ ActorProps = actorwireWith(Actor.props _)

并获得不同的编译错误:

too many arguments for method props: (implicit ec: scala.concurrent.ExecutionContext)akka.actor.Props

我已经尝试将隐式参数显式化并且它工作得很好,除了它有点违反通常的隐式传递执行上下文的做法。

我做错了什么或者是macwire中的问题?

Github中的问题:https://github.com/adamw/macwire/issues/125

1 个答案:

答案 0 :(得分:0)

如果您使用wireWith(A.props _)作为macwire在构造函数使用隐式参数时无法连接actor的解决方法(请参阅macwire issue 121),您可以切换到macwire 2.3.1并连接您的actor使用wireActor[A]wireAnonymousActor[A]wireProps[A]issue 121已在macwire 2.3.1中修复。