Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 104 ยท Dependency Injection

Dependency Injection Concepts

Understand dependency injection for Android: constructor injection, a manual app container, service locator trade-offs, scopes and how DI makes your code testable.

Look at any class in an app and ask: where do its collaborators come from? A NotesViewModel needs a repository. The repository needs a database and an API client. The API client needs an HTTP client and a base URL. Somebody has to create all of these, in the right order, and decide how long each one lives. Dependency injection (DI) is the habit of letting a class receive what it needs instead of creating it itself.

DI is not a framework. It is a design idea, and you can use it with nothing but constructors. Frameworks such as Hilt and Koin (next lesson) only automate the wiring. This lesson teaches the idea and a manual implementation, so that tools like Hilt stop looking like magic. The real Android snippets here are read-only; the TryIts are plain Kotlin on Piston that model the same structure. It builds on Architecture Layers and the repository pattern, and the Kotlin interfaces lesson if abstractions are new to you.

The problem: classes that build their own dependencies

Here is a ViewModel that creates what it needs:

Kotlin
// read-only
class NotesViewModel : ViewModel() {
    private val repository = NotesRepository(
        api = Retrofit.Builder().baseUrl("https://api.example.com/").build().create(NotesApi::class.java),
        dao = Room.databaseBuilder(???, AppDatabase::class.java, "app.db").build().notesDao(),
    )
}

Even in a sketch, the problems show. The ViewModel is tied to concrete classes, so you cannot run it in a unit test without a real network and database. It needs a Context it does not have (the ???). Every other ViewModel that builds its own repository creates another copy, with separate caches and a second database connection. And a change to how the repository is built (a new constructor parameter) forces changes in every class that builds one.

The cure is to turn the dependency into a constructor parameter:

Kotlin
// read-only
class NotesViewModel(private val repository: NotesRepository) : ViewModel() { /* ... */ }

Now the class states what it needs and does not care how it was made. That single change is dependency injection. If the parameter's type is an interface (NotesRepository as an interface with a real and a fake implementation), the class does not even know which implementation it got.

The first TryIt shows the practical payoff: the same class, used with a real-looking implementation and with a fake that makes a test short and deterministic.

Kotlin Constructor injection and a fake (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Greeter cannot be tested if it calls the system clock and writes to disk itself, because the answer would depend on the time of day. With injection, the test decides both. Passing things in also makes the dependencies visible: you read the constructor and know what the class uses. A class with eight constructor parameters is telling you it does too much.

Who creates the objects? Manual DI

Constructors only move the problem: somebody must still build NotesRepository and pass it in. In a small app that somebody is a container: a class that knows how to create and cache the app's objects. You create it once in your Application class, and every activity or ViewModel factory asks it for what it needs.

Kotlin
// read-only: the usual manual setup
class AppContainer(context: Context) {
    private val database by lazy { Room.databaseBuilder(context, AppDatabase::class.java, "app.db").build() }
    private val api by lazy { Retrofit.Builder().baseUrl(BASE_URL).build().create(NotesApi::class.java) }

    val notesRepository: NotesRepository by lazy { DefaultNotesRepository(api, database.notesDao()) }
}

class NotesApp : Application() {
    lateinit var container: AppContainer
    override fun onCreate() {
        super.onCreate()
        container = AppContainer(this)
    }
}

by lazy creates each object on first use and then keeps it, so two screens asking for notesRepository get the same instance. The container is the composition root: the single place in the program that knows concrete classes and connects them. Everything else depends only on abstractions.

flowchart TD
    APP["Application<br/>creates AppContainer"] --> C["AppContainer"]
    C --> DB[("Database")]
    C --> API["NotesApi"]
    DB --> R["NotesRepository"]
    API --> R
    R --> VMF["ViewModel factory"]
    VMF --> VM["NotesViewModel"]
    VM --> UI["Screen"]

Only the container knows how things are built. The ViewModel and the screen just receive them.

ViewModels are created by the system's ViewModelProvider, not by you, so you teach it how through a factory (see ViewModel):

Kotlin
// read-only
val Factory = viewModelFactory {
    initializer {
        val app = this[APPLICATION_KEY] as NotesApp
        NotesViewModel(app.container.notesRepository)
    }
}

Scopes: how long does an object live?

Not every object should live as long as the app. There are three common lifetimes:

  • Unscoped (factory): a new instance every time it is requested. Good for cheap, stateless helpers.
  • Scoped to the app (singleton): one instance for the process. Right for expensive or stateful shared things: the database, the HTTP client, the repository that holds a cache.
  • Scoped to a screen or flow: created when the screen opens and dropped when it closes. Right for things that hold per-screen state, such as a checkout flow object shared by three screens.

Scoping matters for correctness, not only speed. Two instances of a repository mean two caches that disagree. A singleton holding a reference to an Activity is a memory leak, because the activity can never be garbage collected. A singleton should only hold the application Context (it lives as long as the process), never an activity.

The second TryIt is a small manual container with all three lifetimes. Each constructor prints when it runs, so you can see exactly how many instances were created.

Kotlin A manual container with scopes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The database and the repository are created exactly once, however many screens ask. The cart session is shared inside a flow, but a new flow gets a fresh one. Format helpers are never shared. Hilt expresses the same three lifetimes with annotations (@Singleton, @ViewModelScoped, no annotation), and you will meet it in the next lesson.

Service locator: the tempting alternative

A service locator is a global registry the class asks for what it needs:

Kotlin
// read-only
class NotesViewModel : ViewModel() {
    private val repository = ServiceLocator.notesRepository   // looks it up itself
}

It is easy to write and avoids long constructors, but it hides things. The class does not declare its dependencies, so you can only learn what it needs by reading the body. A test must set up a global registry and remember to reset it. A missing registration fails at runtime, when the code path runs, not at compile time. Because the registry is global mutable state, tests that run in parallel can interfere with each other.

Constructor injection makes all that explicit and checkable. Prefer it, and use a locator-style lookup only at the edges where Android creates objects for you and you cannot pass parameters, which is the same situation the ViewModel factory above handles in one place.

What DI buys you

  • Testability. Replace the network, database and clock with fakes, with no mocking tricks (see Unit Testing ViewModels and Flows).
  • Replaceability. Swap an implementation (a different API client, an in-memory database for demos) in one place.
  • Controlled lifetimes. One owner decides what is shared and what is disposed.
  • Clarity. Constructors show what a class depends on, which makes bloated classes visible.

And it has costs: more small classes and interfaces, and some setup code. Do not create an interface for everything. Introduce one when there is a second implementation you actually need (a fake for tests counts).

When to use a framework

Manual DI works well for small and medium apps, and it is a perfectly good choice: it is plain Kotlin, compiles fast and is easy to debug. As the graph grows, the container fills with boilerplate, and scoped containers (one per screen or flow, as above) get tedious. That is the point where a library helps. Hilt generates the wiring at compile time and Koin resolves it at runtime; both are covered in the next lesson. The concepts here (constructor injection, a composition root, scopes) stay the same either way.

Common mistakes

  • Creating dependencies with val x = Foo() inside the class, which defeats injection.
  • Passing the whole container into every class. Then everything can reach everything, which is a service locator in disguise. Pass only what each class needs.
  • Singletons that capture an Activity or a view, which leaks it. Use the application context in app-scoped objects.
  • Over-scoping: making everything a singleton "to be safe". Stateful objects that are shared by accident cause confusing bugs.
  • Under-scoping: creating a new repository per screen, so caches are not shared.
  • Interfaces for classes that will never have a second implementation.
  • Circular dependencies (A needs B and B needs A). Redesign: extract the shared part into a third class.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the core idea of dependency injection?

    DI is a design idea: pass collaborators in (usually through the constructor). Frameworks only automate the wiring.
  2. 2. What does 'by lazy' do in a manual AppContainer?

    A lazy property is initialized the first time it is read and the value is kept, which gives you a singleton within the container.
  3. 3. What is the composition root?

    The composition root (here the AppContainer) is the one place that creates objects and connects them. The rest of the code depends on abstractions.
  4. 4. What is a main drawback of a service locator compared with constructor injection?

    With a locator the class asks a global registry from inside its body, so the constructor does not show what it needs and tests must manage global state.
  5. 5. Why is a singleton holding a reference to an Activity a problem?

    A singleton lives as long as the process. If it holds an Activity, the destroyed Activity (and its views) stay in memory. App-scoped objects should hold the application context only.

Summary

  • Dependency injection means a class receives its collaborators (usually as constructor parameters) instead of building them.
  • It makes classes testable with fakes, replaceable and honest about what they depend on.
  • A manual container created in Application is the composition root; by lazy gives app-scoped singletons, and a ViewModel factory connects it to the system.
  • Choose scopes deliberately: unscoped for cheap helpers, app scope for shared stateful objects, screen or flow scope for per-flow state.
  • Prefer constructor injection to a service locator, which hides dependencies and fails at runtime.
  • Manual DI is fine for small apps; use Hilt or Koin when the wiring becomes repetitive.
  • The Android snippets are read-only; the TryIts are plain Kotlin stand-ins on Piston.

Next: Hilt