Using Koject on Android
Integrating Koject into your Android application is easy.
Getting Started
To get started, add the following dependencies for Android:
dependencies {
implementation("com.moriatsushi.koject:koject-android-core:1.3.0")
}
Also, make sure to check the Setup document.
Call Koject.start()
in the Application
class, and be sure to call application()
.
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Koject.start {
application(this@MyApplication)
}
}
}
To provide the necessary dependencies, use the @Provides
annotation.
You can inject the Application
and the application's Context
.
@Provides
@Singleton
fun provideAppDatabase(
applicationContext: Context
): AppDatabase {
return Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"database-name"
).build()
}
@Provides
class MyController(
val db: AppDatabase
) {
/* ... */
}
To inject into an Activity
, etc., use the inject()
or lazyInject()
method.
class MyActivity: Activity {
val controller: MyController by lazyInject()
/* ... */
}