Basic Dagger Codelab — Part 1

Pimorn Senakat
2 min readOct 7, 2018

--

Setup

Add following lines to `app/build.gradle` (check dagger version here)

apply plugin: 'kotlin-kapt'compile "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"

Implement Injection 1

Step 1: Create Component interface

@Component
interface AppComponent {
...
}

Step 2: Create Module class to provide Employee instance

@Module
internal class DataModule {

@Provides
fun provideEmployee(): Employee {
return Employee()
}
}

Step 3: Add Module to Component

@Component(modules = [DataModule::class]
interface AppComponent {
fun getEmployee(): Employee
}

Step 4: Initial dagger in MainActivity.kt

val appComponent = DaggerAppComponent.create()
val employee = appComponent.getEmployee()

Implement Injection 2

Step 1: Provide Customer in Module

@Module
internal class DataModule {

...
@Provides
fun provideCustomer(): Customer {
return Customer()
}
}

Step 2: Add @Inject in MainActivity.kt

@Inject
lateinit var customer: Customer

Step 3: Add injection to Component

@Component(modules = [DataModule::class]
interface AppComponent {
fun getEmployee(): Employee fun inject(mainActivity: MainActivity)}

Step 4: Call injection in MainActivity.kt

...appComponent.inject(this)

Test using @Singleton and find difference

Annotation Summary

@Module

Used on classes which contains methods annotated with @Provides.

@Provides

Can be used on methods in classes annotated with @Module and is used for methods which provides objects for dependencies injection.

@Singleton

Single instance of this provided object is created and shared.

@Component

Used on an interface. This interface is used by Dagger 2 to generate code which uses the modules to fulfill the requested dependencies.

--

--