Skip to content

Dagger ‐ Constructor injection

Devrath edited this page Oct 5, 2023 · 9 revisions

Observations

  • You can clearly see there are three implementations(Wheels, Engine, and Car).
  • The Engine and the Wheels are passed in the constructor of the Car class.
  • All the three implementations are annotated with @Inject annotation. This notifies the dagger that these classes are available for the dagger to build objects.
  • Thus, The Wheels and the Engine are injected in the constructor of the Car class.
  • The CarComponent class is an interface annotated with @Component.
  • The component class returns the Car object that gets created by dagger.
  • Now a class is generated called DaggerCarComponent which will implement the CarComponent interface and return a Car object. During the car object creation time if any further dependencies are there that need to be created, dagger takes care of it.
// Create function invokes a builder pattern & GetCar function gets the object 
val car: Car = DaggerCarComponent.create().getCar()
// With the help of the reference, one could access all methods of car object
car.start()

Output

Wheels constructor is invoked !
Engine constructor is invoked !
Car constructor is invoked !
Car is Driving

Code

implementations

Engine.kt

class Engine @Inject constructor() {

    init {
        printLog("Engine constructor is invoked !")
    }

}

Wheels.kt

class Wheels @Inject constructor() {

    init {
        PrintUtils.printLog("Wheels constructor is invoked !")
    }

}

Car.kt

class Car @Inject constructor(
    var wheels: Wheels,
    var engine: Engine
) {

    init {
        printLog("Car constructor is invoked !")
    }

    fun start() {
        printLog("Car is Driving")
    }

}

Components

CarComponent

@Component
interface CarComponent {
    fun getCar() : Car
}

Activity

MyActivity.kt

class MyActivity : AppCompatActivity() {

    private lateinit var binding: ActivityDaggerConceptsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDaggerConceptsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setOnClickListener()
    }

    private fun setOnClickListener() {
        binding.apply {
            // Constructor Injection
            constructorInjectionId.setOnClickListener {
                val car: Car = DaggerCarComponent.create().getCar()
                car.start()
            }
        }
    }
    
}
Clone this wiki locally