通过Module.scala对有界泛型类型进行依赖注入

时间:2019-08-03 16:15:04

标签: dependency-injection guice playframework-2.5

如果能在以下方面获得帮助,我将不胜感激。我正在尝试对具有受限参数类型的特征进行依赖注入。

trait ImageDAO[T <: ImageSet] {

  def find(id: String): ImageDisplay[T]

  def find(req: ImageSearch): ImageResponse[T]
}

class ProductImageDAO @Inject() (environment: Environment) extends ImageDAO[ProductImageSet] {
...
}

class ProfileImageDAO @Inject() (environment: Environment) extends ImageDAO[ProfileImageSet] {
...
}

现在,服务特征及其实现

trait ImageService[A <: ImageSet] {
  def retrieve(id: String): ImageDisplay[A]

  def retrieve(req: ImageSearch): ImageResponse[A]
}

class ImageServiceImpl[T <: ImageSet] @Inject() (imageDAO: ImageDAO[T]) extends ImageService[T] {

  def retrieve(id: String): ImageDisplay[T] = imageDAO.find(id)

  def retrieve(req: ImageSearch): ImageResponse[T] = ???
}

case class ProductImageSet(swatchImage: BaseImage, smallImage: BaseImage, mediumImage: BaseImage, largeImage: BaseImage) extends ImageSet

case class ProfileImageSet(smallImage: BaseImage, mediumImage: BaseImage) extends ImageSet

这是我希望进行依赖注入的类Module.scala。

class MyModule extends AbstractModule {
  protected override def configure() {
    bind(new TypeLiteral[ImageDAO[ProductImageSet]](){}).to(classOf[ProductImageDAO]).asEagerSingleton()
    bind(new TypeLiteral[ImageService[ProfileImageSet]](){}).to(classOf[ImageServiceImpl[ProfileImageSet]]).asEagerSingleton()
    bind(new TypeLiteral[ImageService[ProductImageSet]](){}).to(classOf[ImageServiceImpl[ProductImageSet]]).asEagerSingleton()
   }

}

0 个答案:

没有答案