Binding a trait to an object with Scala Guice

Viewed 5107

This was going to be a question about how to get the binding to work, but in cleaning up my example ready to post I've actually managed to get it working - the problem is I have no idea why this works:

import org.specs2.mutable._
import com.google.inject.{ Inject, Module, Binder, Guice }
import net.codingwell.scalaguice.ScalaModule

object InjectorSpec extends Specification {
  val injector = Guice.createInjector(new ScalaModule() {
    def configure() {
      bind[Message].toInstance(MessageImpl)
      bind[MessageService.type].toInstance(MessageService) // This line makes it work?
    }
  })

  trait Message {
    val body: String
  }

  object MessageImpl extends Message {
    val body: String = "Hello!"
  }

  object MessageService {
    @Inject
    val message: Message = null

    def get = message.body
  }

  "MessageService" should {
    "Inject Message Implementation" in {
      MessageService.get mustEqual "Hello!"
    }
  }
}

Initially I was just binding the type to be injected (inject MessageImpl for Message). Somewhere along the way I picked up the second bind which is for the service, that isn't injected (so I don't understand the bind being required). Can anyone explain what's happening here and if this is the correct way to proceed?

1 Answers
Related