Dependency injection cheat sheet
Key ideas
- Constructor injection is the default in Hilt (
@Inject constructor) and Koin (singleOf,factoryOf); field injection is only for system-created classes likeActivityandFragment. - 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.
- The composition root is the one place where concrete types are chosen and wired together:
@HiltAndroidApp+@Module/@InstallInin Hilt, or anAppContainerobject in manual DI. - Unscoped is the default (new instance per request); scope to
@Singletonorsingleonly when the object is expensive to create or sharing state is intentional. @Bindsmaps an interface to an@Inject-constructed implementation with no method body;@Providesis for types you cannot annotate (third-party, platform objects).@InstallIndecides which component a module belongs to; it does NOT make bindings singletons—add@Singletonexplicitly.- Koin resolves at runtime and a missing definition fails only when first resolved (or in a
verify()test); Hilt fails the build. - Koin works in Kotlin Multiplatform shared code; Hilt is Android-only and cannot run in shared iOS code.
- Most unit tests need no DI framework: call the constructor with a fake. Hilt's
@HiltAndroidTestwith@TestInstallInor@UninstallModulesis for tests that exercise real wiring. @ActivityRetainedScopedsurvives configuration changes and is released when the Activity finishes, but it does not survive process death; useSavedStateHandle, DataStore, or Room for that.
APIs at a glance
| API or term | Use it for |
|---|---|
@Inject constructor | Marks a class so Hilt can create it automatically; no @Provides method needed. |
@Binds | Maps an interface to its @Inject-constructed implementation in an abstract module; generates less code than @Provides. |
@Provides | Supplies types Hilt cannot build from a constructor (third-party libraries, platform objects like Retrofit). |
@InstallIn | Required on every @Module; tells Hilt which component the module belongs to (e.g. SingletonComponent::class). |
@Singleton | One instance per SingletonComponent (per process); use for OkHttpClient, Room database, cached repositories. |
@ActivityRetainedScoped | Survives configuration changes, released when the Activity finishes; use for WebSocket connections or in-memory caches tied to a screen. |
@ViewModelScoped | One instance shared among all dependencies of a single ViewModel; two different ViewModels get two instances. |
@HiltViewModel | Marks a ViewModel for Hilt injection; supports @AssistedFactory for caller-supplied values. |
single / factory / viewModel | Koin 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 varfor system-created classes (Activity,Fragment,Service). - Never scope everything to
@Singletonorsingle; leave cheap, stateless objects unscoped or usefactory. - Prefer
@Bindsover@Provideswhen the implementation already has an@Injectconstructor; it needs no method body and generates less code. - Never call
get()orinject()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 repoleaves 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 /
factorybehaviour. - Writing a @Provides method for a class that already has an @Inject constructor. The redundant
@Providessilently wins over the@Injectconstructor, so a later change to the constructor or a scope annotation on the class is ignored. Fix: delete the@Providesand let Hilt build the class automatically. - Thinking @InstallIn(SingletonComponent::class) makes bindings singletons.
@InstallInonly decides which component the module belongs to; without@Singletonon the@Providesmethod or the class, a new instance is created every time. Fix: add@Singletonexplicitly 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
startKointhrows because a Koin application is already running, causing cascading test failures. Fix: useKoinTestRuleor callstopKoin()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.