Why dependency injection

Learn why dependency injection matters in Android: constructor injection improves testability and decoupling, and prepares you for Hilt or Koin. About 25 minutes.

Why it matters

  • A class that instantiates its own collaborators cannot be tested with a fake; DI is the minimum change that makes unit tests possible without a device or network.
  • Interviewers at mid and senior levels ask you to explain the difference between DI and a service locator, and to show why constructor injection beats field injection. Getting this wrong signals you have not read a ViewModel test.
  • Every DI framework (Hilt, Koin) is a wiring tool. If you do not understand the manual pattern first, you will misuse @Provides, @Inject, or single / factory and create hidden coupling that the framework hides but does not remove.
  • Production bugs where a singleton network client held a stale token, or a ViewModel created its own repository and could not be tested, trace back to a missing DI boundary.

The simple explanation

  • A restaurant kitchen: the chef (your class) does not grow the tomatoes (create the dependency). The supplier (the DI container) delivers them through the pass (the constructor).

The core idea

Dependency injection (DI) means a class receives its collaborators from the outside instead of constructing them itself. The most common form is constructor injection: the dependency is a val parameter in the primary constructor.

Service locator is the alternative: the class calls a global registry at runtime to fetch what it needs (ServiceLocator.get<NetworkClient>()). The registry can return an interface, but the class now depends on the registry itself, its dependencies no longer show up in its constructor, and a missing registration is only found when that line runs.

ApproachWho creates the dependencyTestable?Coupling
Hardcoded instantiationThe class itselfNoTight
Service locatorA global registryPossible, but tests must set up shared global stateHidden (on the registry)
Constructor injectionThe caller / containerYes (pass a fake)Loose

Manual DI (the pattern before any framework)

At the app level you create a small container object that builds and holds instances. Each screen or ViewModel receives its dependencies through the constructor. This is exactly what Hilt or Koin automate later, and doing it by hand once teaches you what @Inject and @Module do for you.

Why it matters in code

  • Testability: a FakeNetworkClient is passed in place of the real one; the test is a plain JVM test with no device, network or Robolectric.
  • Single responsibility: the class does not decide which implementation to use; that decision lives at the composition root.
  • Lifecycle clarity: the container decides how long an object lives and who shares it. A class that creates its own dependency makes a private copy that nothing else can share or replace.

The cost is wiring code. In a small app that is a few dozen lines. In a large app it is what Hilt or Koin save you from writing by hand.

Notes

  • Constructor injection is the default in Hilt (@Inject constructor) and in Koin (single { Repo(get()) } or singleOf(::Repo)). Field injection (@Inject lateinit var) is only for classes the system creates, such as an Activity or Fragment, where you do not control the constructor.
  • A service locator hides coupling behind a global get() call. The class depends on the registry existing and being set up, and its constructor no longer tells you what it needs. With DI the class just declares its dependencies and the caller decides the implementation.
  • Unscoped objects (a new instance every time) are the default. Scoping to @Singleton or single means one instance for the whole process; use it when the object is expensive to create (an OkHttpClient, a Room database) or when sharing state is intentional.
  • The composition root is the one place in the app where concrete types are chosen and wired together. In Hilt that is @HiltAndroidApp plus @Module / @InstallIn. In manual DI it is your AppContainer object.
  • A class that instantiates a concrete dependency inside its body cannot be unit-tested with a fake without reflection or a test-only constructor. That is the single most common reason a team adds DI to an existing codebase.
  • Hilt's @Inject constructor on a class means Hilt can create it automatically. You do not need a @Provides method for that class. @Provides is for types you cannot annotate (third-party, platform objects).
  • @Binds tells Dagger "when someone asks for this interface, use this implementation". It needs no method body, and Dagger generates less code for it than for an equivalent @Provides. Use it when an @Inject-constructed class implements an interface.
  • In Koin, single is one instance per Koin container, factory creates a new instance each call, and viewModel creates a ViewModel held by its ViewModelStoreOwner. A missing definition fails only when it is first resolved (or in a verify() test), while Hilt fails the build.
  • Most unit tests need no framework at all: call the constructor with a fake. Hilt's @HiltAndroidTest with @TestInstallIn or @UninstallModules is for tests that exercise the real wiring.
  • Kotlin Multiplatform projects often choose Koin over Hilt because Hilt is Android-only (it cannot run in shared iOS code). The DI concept is identical; only the wiring syntax differs.

Code example

This shows a manual DI container for a small feature: an interface, two implementations, and a container that picks the right one. It is the pattern Hilt or Koin replace at scale.

// A stand-in for a real network client (Retrofit, Ktor) to keep the example short
class ApiService(private val baseUrl: String) {
    fun fetch(userId: String): String = "user $userId from $baseUrl"
}
 
// 1. Define the contract (interface, not a class)
interface UserRepository {
    fun load(userId: String): String
}
 
// 2. Real implementation talks to a network
class NetworkUserRepository(private val api: ApiService) : UserRepository {
    override fun load(userId: String): String = api.fetch(userId)
}
 
// 3. Fake for tests: no network, no device
class FakeUserRepository(private val data: Map<String, String>) : UserRepository {
    override fun load(userId: String): String =
        data[userId] ?: throw NoSuchElementException(userId)
}
 
// 4. The consumer depends on the interface, not the impl
class UserViewModel(private val repo: UserRepository) {
    fun getUser(id: String): String = repo.load(id)
}
 
// 5. Composition root: one place chooses the implementation
object AppContainer {
    // Created once and shared, like a @Singleton
    private val api by lazy { ApiService("https://api.example.com/") }
 
    fun userRepo(): UserRepository = NetworkUserRepository(api)
 
    fun userViewModel(): UserViewModel =
        UserViewModel(userRepo())
}
 
// 6. Test: swap the fake in, no framework needed
fun testUserViewModel() {
    val fake = FakeUserRepository(mapOf("42" to "Alice"))
    val vm = UserViewModel(fake)
    check(vm.getUser("42") == "Alice")
}
  • UserViewModel never sees NetworkUserRepository; it only knows UserRepository. That is the boundary DI creates.
  • AppContainer is the composition root: the only place that names concrete classes. The lazy api is shared, while userRepo() and userViewModel() build a new object per call, the same split as scoped and unscoped bindings in Hilt.
  • In a real app UserViewModel would extend ViewModel and be created through a ViewModelProvider.Factory (or hiltViewModel()), but the constructor stays the same.

Run the idea in plain Kotlin

Production code gets the real gateway from the container; the test hands the same OrderService a fake. OrderService never changes.

interface PaymentGateway {
  fun charge(amount: Int): Boolean
}

class RealGateway(private val apiKey: String) : PaymentGateway {
  override fun charge(amount: Int): Boolean {
      println("  real gateway called with key " + apiKey.take(7) + "...")
      return true
  }
}

class FakeGateway(private val succeed: Boolean) : PaymentGateway {
  val charged = mutableListOf<Int>()
  override fun charge(amount: Int): Boolean {
      charged.add(amount)
      return succeed
  }
}

// Depends only on the interface and receives it through the constructor
class OrderService(private val gateway: PaymentGateway) {
  fun place(amount: Int): String =
      if (gateway.charge(amount)) "order placed" else "payment declined"
}

// Composition root: the one place that picks concrete classes
object Container {
  private val gateway: PaymentGateway by lazy { RealGateway("sk_live_abc123") }
  fun orderService() = OrderService(gateway)
}

fun main() {
  println("Production:")
  println("  " + Container.orderService().place(5000))

  println("Test, gateway succeeds:")
  val ok = FakeGateway(succeed = true)
  println("  " + OrderService(ok).place(5000) + ", charged " + ok.charged)

  println("Test, gateway declines:")
  val declined = FakeGateway(succeed = false)
  println("  " + OrderService(declined).place(700) + ", charged " + declined.charged)
}

Expected output:

Production:
  real gateway called with key sk_live...
  order placed
Test, gateway succeeds:
  order placed, charged [5000]
Test, gateway declines:
  payment declined, charged [700]

In production

Stale auth token in a singleton network client
  • Users reported that after logging out and logging in as a different account, the app still showed the previous user's data for a short period.
  • Dashboards showed a spike in 401 errors followed by a burst of 200s with the wrong user ID.
  • Root cause: the @Singleton network client copied the auth token into a header when it was built. A new login saved the new token, but the client kept sending the old one until the process died.
The fix
  • The team reproduced it by logging out, logging in as user B, and immediately calling the profile screen.
  • They kept the OkHttpClient as a singleton (rebuilding it per request would throw away its connection pool) and injected a TokenProvider interface into an OkHttp Interceptor that reads the current token on every request.
  • Logout now clears the token store and the in-memory caches, so nothing from user A survives into user B's session.
  • They added a unit test with a fake TokenProvider that returns a different token on each call, using MockWebServer to assert each request carries the latest one.
  • The DI boundary already existed; the bug was a singleton that captured changing state when it was built.
ViewModel created its own repository, blocking unit tests
  • A CheckoutViewModel instantiated CheckoutRepository in its body, so every test needed a real database and a network stub.
  • ViewModel tests were slow and flaky because each one needed an in-memory database and a stubbed server.
  • Developers skipped tests rather than fix the wiring, so the checkout flow had zero unit coverage.
The fix
  • They extracted a CheckoutRepository interface and made the concrete class implement it.
  • The ViewModel constructor now takes CheckoutRepository instead of creating it.
  • Tests pass a FakeCheckoutRepository backed by in-memory maps and run as plain JVM tests.
  • Code review now rejects a ViewModel that constructs its own repository or use case.

Common mistakes

  • Field injection where constructor injection works. An @Inject lateinit var repo: Repo leaves the object unusable until injection runs and hides the dependency from the constructor. Keep field injection for system-created classes (Activity, Fragment, Service); everywhere else use constructor injection.
  • Scoping everything to @Singleton or single. A singleton that stores per-user or per-screen state (a user id, a token copied at creation, screen data) serves it stale to the next user or screen, and it stays in memory for the whole process. Scope when sharing or the creation cost justifies it; otherwise use the default unscoped / factory behaviour.
  • Using a service locator and calling it DI. A ServiceLocator.get<T>() call inside the class couples it to the registry and hides what it needs. With DI the dependency is passed in; the class never asks for it.
  • Injecting an interface but the only implementation is a singleton that holds mutable state. The interface hides the type but the singleton still shares mutable state across screens, causing race conditions and test flakiness. Check the scope, not just the type.
  • Writing a @Provides method for a class that already has an @Inject constructor. Hilt can already build it. A redundant @Provides silently wins over the @Inject constructor, so a later change to the constructor (or a scope annotation on the class) is ignored. Two modules providing the same type is a duplicate-binding build error.
  • Deferring DI until the app is big. Constructor injection costs nothing even without a framework; you can add Hilt or Koin later. Classes that construct their own collaborators are what make the later migration expensive.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between dependency injection and a service locator?”

“Why constructor injection over field or property injection?”

“How does DI make unit testing easier? Give a concrete example.”

“When would you choose Koin over Hilt, or vice versa?”

Quiz

A class calls ServiceLocator.get<NetworkClient>() inside its method. What is the main problem?

Which injection style makes a Kotlin object immutable and fully initialised after construction?

In Hilt, what is the difference between @Provides and @Binds?

A ViewModel creates its repository with CheckoutRepository() inside its body. What is the immediate consequence?

0 of 4 answered

Mini task

15-minute exercise: manual DI for a login feature

  1. Create a new Kotlin file. Define an interface AuthRepository with one method: fun login(email: String, password: String): String (returns a token string).

  2. Implement NetworkAuthRepository that takes a baseUrl: String in its constructor and returns a hardcoded token string. Add a comment saying "replace with real HTTP call".

  3. Implement FakeAuthRepository that takes a Map<String, String> (email to token) in its constructor and looks up the token. Throw NoSuchElementException if the email is missing.

  4. Create LoginViewModel that takes AuthRepository in its constructor. Add a fun login(email: String, password: String): String that delegates to the repository.

  5. Create an object AppContainer with a function loginViewModel(): LoginViewModel that wires NetworkAuthRepository into LoginViewModel.

  6. Write a fun main() that:

    • Calls AppContainer.loginViewModel().login("a@b.com", "pw") and prints the result.
    • Creates a FakeAuthRepository with mapOf("a@b.com" to "tok_123"), passes it to a new LoginViewModel, calls login, and prints the result.
    • Prints whether both results are equal.

Done condition: main() runs and prints three lines: the network token, tok_123 from the fake, and false. No Android SDK or framework is needed, and LoginViewModel never calls a repository constructor itself.

Next: Hilt basics