title: PlayFramework: how to inject database object
body: <p>I'm using anorm for play framework and I have the following service class:</p>
  
  <pre><code>@javax.inject.Singleton
  class ProductService @Inject() (dbApi: DBApi) {
  
    private val DB = dbApi.database("default")
  
    def save(product: Product) = {
      DB.withConnection { implicit connection =&gt;
        ....
      }
    }
  }
  </code></pre>
  
  <p>Two issues here:</p>
  
  <p>1) I do not wish to add the line <code>private val DB = dbApi.database("default")</code> in each Service class. What is the best way to abstract this?</p>
  
  <p>2) I would also like to have the datasource configurable so that I can pass test datasource when writing Integration tests</p>
  
  <p>Test class:</p>
  
  <pre><code>import models.ProductService
  import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
  import play.api.db.Databases
  
  class ProductSpec extends PlaySpec with OneAppPerSuite {
  
    var productService: ProductService = app.injector.instanceOf(classOf[ProductService])
  
    Databases.withDatabase(
      driver = "com.mysql.jdbc.Driver",
      url = "jdbc:mysql://localhost/playtest",
      config = Map(
        "user" -&gt; "test",
        "password" -&gt; "demo"
      )
    ) { database =&gt;
      import play.api.db.evolutions._
      Evolutions.applyEvolutions(database)
  
      "Product" should {
        "be retrieved by Id" in {
          val product = productService.get(23)
          product.get.name must equal("mobile")
        }
      }
    }
  
  }
  </code></pre>
  
  <p>Any suggestions?</p>