Dependency injection cheat sheet

Revise dependency injection in Android: constructor injection, Hilt scopes, @Binds, @Provides, Koin single/factory, and testable composition roots.

Key ideas

  1. Constructor injection is the default in Hilt (@Inject constructor) and Koin (singleOf, factoryOf); field injection is only for system-created classes like Activity and Fragment.
  2. A class that instantiates a concrete dependency inside its body cannot be unit-tested with a fake without reflection or a test-only constructor; this is the main reason teams add DI.
  3. The composition root is the one place where concrete types are chosen and wired together: @HiltAndroidApp + @Module/@InstallIn in Hilt, or an AppContainer object in manual DI.
  4. Unscoped is the default (new instance per request); scope to @Singleton or single only when the object is expensive to create or sharing state is intentional.
  5. @Binds maps an interface to an @Inject-constructed implementation with no method body; @Provides is for types you cannot annotate (third-party, platform objects).
  6. @InstallIn decides which component a module belongs to; it does NOT make bindings singletons—add @Singleton explicitly.
  7. Koin resolves at runtime and a missing definition fails only when first resolved (or in a verify() test); Hilt fails the build.
  8. Koin works in Kotlin Multiplatform shared code; Hilt is Android-only and cannot run in shared iOS code.
  9. Most unit tests need no DI framework: call the constructor with a fake. Hilt's @HiltAndroidTest with @TestInstallIn or @UninstallModules is for tests that exercise real wiring.
  10. @ActivityRetainedScoped survives configuration changes and is released when the Activity finishes, but it does not survive process death; use SavedStateHandle, DataStore, or Room for that.

APIs at a glance

API or termUse it for
@Inject constructorMarks a class so Hilt can create it automatically; no @Provides method needed.
@BindsMaps an interface to its @Inject-constructed implementation in an abstract module; generates less code than @Provides.
@ProvidesSupplies types Hilt cannot build from a constructor (third-party libraries, platform objects like Retrofit).
@InstallInRequired on every @Module; tells Hilt which component the module belongs to (e.g. SingletonComponent::class).
@SingletonOne instance per SingletonComponent (per process); use for OkHttpClient, Room database, cached repositories.
@ActivityRetainedScopedSurvives configuration changes, released when the Activity finishes; use for WebSocket connections or in-memory caches tied to a screen.
@ViewModelScopedOne instance shared among all dependencies of a single ViewModel; two different ViewModels get two instances.
@HiltViewModelMarks a ViewModel for Hilt injection; supports @AssistedFactory for caller-supplied values.
single / factory / viewModelKoin scopes: one per container, new per call, or a ViewModel held by its ViewModelStoreOwner.
hiltViewModel()Compose function (from hilt-lifecycle-viewmodel-compose) to obtain a @HiltViewModel; in Activity/Fragment use by viewModels().
koinViewModel()Compose function to obtain a Koin-declared ViewModel from the current ViewModelStoreOwner.
verify()Koin test that checks all definitions resolve; add extraTypes for runtime-supplied types like SavedStateHandle.

Snippets

Interface, real impl, fake, and a test with no framework

interface ApiService { fun fetch(userId: String): String }
interface UserRepository { fun load(userId: String): String }
class NetworkUserRepository(private val api: ApiService) : UserRepository {
    override fun load(userId: String): String = api.fetch(userId)
}
class FakeUserRepository(private val data: Map<String, String>) : UserRepository {
    override fun load(userId: String): String = data[userId] ?: throw NoSuchElementException(userId)
}
class UserViewModel(private val repo: UserRepository) {
    fun getUser(id: String): String = repo.load(id)
}
fun testUserViewModel() {
    val vm = UserViewModel(FakeUserRepository(mapOf("42" to "Alice")))
    check(vm.getUser("42") == "Alice")
}

Hilt: @Binds for interface mapping, @Provides for third-party objects

interface Clock { fun now(): Long }
class RealClock @Inject constructor() : Clock {
    override fun now(): Long = System.currentTimeMillis()
}
 
@Module
@InstallIn(SingletonComponent::class)
abstract class CoreModule {
    @Binds
    abstract fun bindClock(impl: RealClock): Clock
}
 
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides @Singleton
    fun provideOkHttp(): OkHttpClient = OkHttpClient.Builder().build()
 
    @Provides @Singleton
    fun provideRetrofit(client: OkHttpClient): Retrofit =
        Retrofit.Builder().baseUrl("https://api.example.com/").client(client).build()
}

Koin module: single, factory, viewModel, and startKoin in Application

interface Analytics { fun log(event: String) }
class LogcatAnalytics : Analytics {
    override fun log(event: String) { Log.d("Analytics", event) }
}
class DateFormatter
class LoginViewModel(private val analytics: Analytics) : ViewModel()
 
val appModule = module {
    singleOf(::LogcatAnalytics) { bind<Analytics>() }
    factoryOf(::DateFormatter)
    viewModelOf(::LoginViewModel)
}
 
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin { androidContext(this@App); modules(appModule) }
    }
}

Rules of thumb

  • Prefer constructor injection everywhere; reserve @Inject lateinit var for system-created classes (Activity, Fragment, Service).
  • Never scope everything to @Singleton or single; leave cheap, stateless objects unscoped or use factory.
  • Prefer @Binds over @Provides when the implementation already has an @Inject constructor; it needs no method body and generates less code.
  • Never call get() or inject() inside a class body; keep resolution inside module definitions so the constructor shows what the class needs.
  • Prefer a verify() test or Koin Annotations / compiler plugin so missing bindings fail CI instead of crashing users at runtime.
  • Never defer constructor injection until the app is big; it costs nothing without a framework and makes a later Hilt or Koin migration cheap.

Gotchas

  • Field injection where constructor injection works. An @Inject lateinit var repo leaves the object unusable until injection runs and hides the dependency from the constructor, making the class hard to unit-test. Fix: use constructor injection everywhere except system-created classes.
  • Scoping everything to @Singleton or single. A singleton that stores per-user or per-screen state serves it stale to the next user and stays in memory for the whole process. Fix: scope only when sharing state is intentional or creation is expensive; otherwise use the default unscoped / factory behaviour.
  • Writing a @Provides method for a class that already has an @Inject constructor. The redundant @Provides silently wins over the @Inject constructor, so a later change to the constructor or a scope annotation on the class is ignored. Fix: delete the @Provides and let Hilt build the class automatically.
  • Thinking @InstallIn(SingletonComponent::class) makes bindings singletons. @InstallIn only decides which component the module belongs to; without @Singleton on the @Provides method or the class, a new instance is created every time. Fix: add @Singleton explicitly where a shared instance is needed.
  • Calling get() or inject() inside ordinary classes in Koin. The class now pulls from a global container, its constructor no longer shows what it needs, and every test must start Koin. Fix: pass dependencies through the constructor and keep get() inside module definitions only.
  • Forgetting stopKoin() between tests. The next startKoin throws because a Koin application is already running, causing cascading test failures. Fix: use KoinTestRule or call stopKoin() in @After.

Quick interview answers

Why prefer constructor injection over field injection in Hilt?

Constructor injection makes dependencies visible in the signature and lets you pass a fake in a unit test with no framework. Field injection (@Inject lateinit var) leaves the object unusable until injection runs and should be reserved for system-created classes like Activity and Fragment.

When should I use @Binds instead of @Provides?

Use @Binds when the implementation class already has an @Inject constructor and implements an interface; it needs no method body and Dagger generates less code. Use @Provides for types you cannot annotate, such as third-party or platform objects like Retrofit or OkHttpClient.

Does @InstallIn(SingletonComponent::class) make every binding in that module a singleton?

No. @InstallIn only tells Hilt which component the module belongs to; without @Singleton on the @Provides method or the class, a new instance is created on every injection request. Add @Singleton explicitly when you need one instance per process.

Why do Kotlin Multiplatform projects often choose Koin over Hilt?

Hilt is Android-only and cannot run in shared iOS or desktop code, while Koin's DI concept is identical and its wiring syntax works in any Kotlin target. The trade-off is that Koin resolves at runtime, so a missing definition fails only when first resolved unless you add a verify() test.

How do you unit-test a ViewModel without a DI framework?

Call the ViewModel's constructor directly with a fake implementation of the repository interface; no Hilt or Koin is needed. For tests that exercise the real wiring, use Hilt's @HiltAndroidTest with @TestInstallIn or @UninstallModules to swap modules.

What is the composition root and where does it live in Hilt?

The composition root is the one place in the app where concrete types are chosen and wired together. In Hilt it is @HiltAndroidApp on the Application subclass plus @Module / @InstallIn annotations; in manual DI it is an AppContainer object.

Go deeper