简体   繁体   中英

Scala Play 2 Guice dependency injection with traits

In my application I have the following traits/concrete classes:

In package models.daos :

trait UserDAO // UserDAO.scala
class UserDAOImpl @Inject() (app: play.api.Appliction) extends UserDAO // UserDAOImpl.scala

In package controllers :

class Application @Inject() (userDao: UserDAO) extends Controller

However, when I run the app I get:

ProvisionException: Unable to provision, see the following errors:

1) No implementation for models.daos.UserDAO was bound.
  while locating models.daos.UserDAO
    for parameter 0 at controllers.Application.<init>(Application.scala:15)
  while locating controllers.Application
    for parameter 1 at router.Routes.<init>(Routes.scala:31)
  while locating router.Routes
  while locating play.api.inject.RoutesProvider
  while locating play.api.routing.Router

I'm new to dependency injection and don't really know how to tell Guice to use the concrete class.

You need to extend AbstractModule

class DaoModule extends AbstractModule {
  def configure() = {
    bind(classOf[UserDAO])
     .to(classOf[UserDAOImpl])
  }
}

in conf/application.conf you need to add:

play.modules.enabled += "modules.DaoModule"

You need to create injector somewhere in your code, typically in Global object of your Play module:

object Global extends GlobalSettings {

  val injector = Guice.createInjector(
    new AbstractModule {
      protected def configure() = {
        bind(classOf[UserDAO]).to(classOf[UserDAOImpl])
      }
    }
  )
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM