Dependency injection

Architecture and dependency injection Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A ViewModel creates ArticleRepository(Retrofit.Builder()...build()) inside itself, and tests hit the real network. Best fix?

Options
Hint 1 of 1

Who should create the repository?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Take the repository as a constructor parameter and provide it with DI

Correct. Tests can pass a fake, and the app shares one instance.

Why not the others?
  • B Add an isTest flag. Test flags leak into production code.
  • C Mock Retrofit's static builder. Fragile, and the design stays coupled.
  • D Make the repository a global object. Still hard to replace in tests.

30-second answer

Dependency injection means a class receives what it needs, usually through its constructor, instead of creating it. That makes dependencies visible, lets tests pass fakes, and lets one place decide lifetimes such as a single HTTP client for the app. On Android, Hilt is the standard library; manual DI with a container class is fine for small apps.

Practise saying it · 30 s. No recording, just a timer

Explain dependency injection.

Say your answer out loud, then check which of these points you covered:

  • Receive dependencies, don't create them
  • Constructor injection
  • Testability and lifetimes
  • Hilt checks at compile time

Deep dive

Constructor injection is the default; field injection is only for framework classes Android creates, like Activities.

A DI graph knows how to build each type and how long instances live.

Service locators (asking a global for dependencies) hide them; DI makes them explicit.

Compile-time DI (Hilt/Dagger) fails the build on missing bindings; runtime DI (Koin) fails at runtime.

Common mistakes

  • Creating dependencies inside classes with Repository() calls.
  • Using field injection everywhere.
  • Injecting a Context of an Activity into a singleton.

Senior take & follow-ups

Name the benefits: testability, lifetimes, visibility. Then the tool choice.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why can't you constructor-inject an Activity?

    Show hint

    The framework creates it, so Hilt injects fields after creation.

  2. Koin vs Hilt?

    Show hint

    Koin is a runtime service locator with a DSL; Hilt checks the graph at compile time.

Compare on iOS: Dependency injection The same idea; iOS usually does it by hand or with a small container.

Suggest a fix if something here is wrong or out of date.