[英]How to bind a class that extends a Trait with a monadic type parameter using Scala 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] ^
解决这个问题的正确方法是什么?
在阅读了这个 SO answer和this one之后,我使用 Guice 的TypeLiteral找到了正确的解决方案。
工作解决方案是:
// In Module.scala configure()
bind(new TypeLiteral[ClientRepository[IO]] {}).to(classOf[ClientRepositoryImpl])
因为我们必须提供一个可以实例化的类(带有一个类型参数,在我们的例子中是IO
)。 TypeLiteral
是一个特殊的类,可让您指定完整的参数化类型,可用于创建到我们Repo[F[_]]
的特定实现的实际绑定。 不能实例化带有泛型参数的类,但我们可以强制 Guice 选择一个特定的ClientRepository
,它是用类型参数cats.effect.IO
。
最后但并非最不重要的是,每当您必须注入特征ClientRepository
您还必须指定类型参数。 例如:
class ClientResourceHandler @Inject()(
routerProvider: Provider[ClientRouter],
clientRepository: ClientRepository[IO]
)
ClientResourceHandler
需要调用 repo,所以我们使用特征ClientRepository[IO]
(不仅仅是ClientRepository
)注入它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.