playframework Dependency Injection - Scala Basic usage

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

A typical singleton class :

import javax.inject._
@Singleton
class BurgersRepository {
    // implementation goes here
}

Another class, requiring access to the first one.

import javax.inject._
class FastFoodService @Inject() (burgersRepository: BurgersRepository){
    // implementation goes here
    // burgersRepository can be used
}

Finally a controller using the last one. Note since we didn't mark the FastFoodService as a singleton, a new instance of it is created each time it is injected.

import javax.inject._
import play.api.mvc._
@Singleton
class EatingController @Inject() (fastFoodService: FastFoodService) extends Controller {
    // implementation goes here
    // fastFoodService can be used
}


Got any playframework Question?