如何使用Scala Guice绑定带有Monadic类型参数扩展了Trait的类?

时间:2019-06-19 13:23:50

标签: scala playframework guice

我需要绑定此特征的实现:

trait ClientRepository[F[_]] {
  def list(): F[Iterable[ClientDTO]]
}

此实现:

import cats.effect.IO

@Singleton
class ClientRepositoryImpl @Inject()(db: OldDataBase, c: IOContextShift)
    extends ClientRepository[IO] {

  override def list(): IO[Iterable[ClientDTO]] = ???
}

我正在使用Scala Play! v2.7.2和Scala v2.12.8,以及scala-guice v4.2.1。为了将特征绑定到其实现,我想在我的Module.scala中做类似的事情:

class Module(environment: Environment, configuration: Configuration)
    extends AbstractModule
    with ScalaModule {

  override def configure() = {

    bind[ClientRepository].to[ClientRepositoryImpl[IO]].in[Singleton]

  }
}

我得到的错误是:

[error] app/Module.scala:37:9: kinds of the type arguments (ClientRepository) do not conform to the expected kinds of the type parameters (type T).
[error] ClientRepository's type parameters do not match type T's expected parameters:
[error] trait ClientRepository has one type parameter, but type T has none
[error]     bind[ClientRepository].to[ClientRepositoryImpl[IO]].in[Singleton]
[error]         ^
[error] app/Module.scala:37:31: ClientRepositoryImpl does not take type parameters
[error]     bind[ClientRepository].to[ClientRepositoryImpl[IO]].in[Singleton]
[error]                               ^
[error]

我也尝试过:

bind[ClientRepository[IO]].to[ClientRepositoryImpl].in[Singleton]

Module.scala:37:9: kinds of the type arguments (cats.effect.IO) do not conform to the expected kinds of the type parameters (type T).
[error] cats.effect.IO's type parameters do not match type T's expected parameters:
[error] class IO has one type parameter, but type T has none
[error]     bind[ClientRepository[IO]].to[ClientRepositoryImpl].in[Singleton]
[error]         ^

bind[ClientRepository[IO[_]]].to[ClientRepositoryImpl].in[Singleton]

Module.scala:37:27: cats.effect.IO[_] takes no type parameters, expected: one
[error]     bind[ClientRepository[IO[_]]].to[ClientRepositoryImpl].in[Singleton]
[error]                           ^

解决此问题的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

在阅读TypeLiteralthis SO answer之后,我使用Guice的this one找到了合适的解决方案。

有效的解决方案是:

    // In Module.scala configure()
    bind(new TypeLiteral[ClientRepository[IO]] {}).to(classOf[ClientRepositoryImpl])

因为我们必须提供一个可以实例化的类(带有类型参数,在我们的例子中为IO)。 TypeLiteral是一个特殊类,可让您指定完整的参数化类型,可用于创建与我们Repo[F[_]]的特定实现的实际绑定。具有泛型参数的类无法实例化,但是我们可以强制Guice选择使用类型参数ClientRepository构建的特定cats.effect.IO

最后但并非最不重要的一点是,每当必须注入特征ClientRepository时,也必须指定type参数。例如:

class ClientResourceHandler @Inject()(
    routerProvider: Provider[ClientRouter],
    clientRepository: ClientRepository[IO]
)

ClientResourceHandler需要调用该仓库,因此我们使用特征ClientRepository[IO](而不仅仅是ClientRepository)注入它。

相关问题