Manual Dependency Injection
Android Development with Compose: Architecture & Data
Course 5 ยท Chapter 9 ยท Handing Objects Over
You have been doing dependency injection since Chapter 5 without the name. The ViewModel does not build its repository: someone hands it one. This chapter names the idea, gathers the scattered wiring into one deliberate place, and shows what it costs, which is the reason Chapter 10 exists.
AppContainer on the Application class that builds dependencies by hand, and the note that you manage it yourself; the framework does not let you pass values into a ViewModel constructor by default, so a ViewModelProvider.Factory is needed;
the viewModelFactory and initializer builder reading from the container through APPLICATION_KEY; the factory passed to viewModel(factory = ...) in Compose; constructor injection recommended; testing by passing fakes or mocks; and Hilt or manual DI both recommended for simple apps, with Hilt generating the factory.
The docs flagged: some pages are old or deprecated and the factory APIs have changed across ViewModel versions. General knowledge, not checked: the exact code and imports below, the object scoping remarks, and the TimeProvider example. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
The Problem
- It cannot be tested without a real Android
Application, a real database and the network. - It cannot be changed without editing the ViewModel: a different repository means a different ViewModel.
- It hides what it needs. You cannot see the dependencies by reading the constructor.
- It may create two databases. If two classes each build their own, they disagree (Chapter 4 said: one database for the whole app).
(general knowledge) These four points are the usual case for dependency injection; they are not quoted from the docs.
Constructor Injection
(docs) The architecture recommendations say to use dependency injection best practices, mainly constructor injection where possible: a class declares what it needs as constructor parameters and does not build them. Injection just means the objects are passed in from outside. Nothing magic, and no library, is required.
An Application Container
Somebody still has to build the objects. (docs) The manual DI guide suggests an AppContainer, created in the Application class, that builds the dependencies by hand. Chapters 5 to 8 had a growing set of by lazy properties on NotesApp and a NetworkModule object; this puts them in one tidy class:
- An interface and a default implementation. The interface is what the app can supply; the class is how. A test can supply a different implementation (general knowledge).
by lazy(general knowledge) builds each object the first time it is used, and exactly once, so there is one database and one Retrofit instance for the whole app.- The container is the only place that knows the full wiring. The ViewModel, the repositories and the screens know only their own parameters.
- The manifest still names the class:
android:name=".NotesApp"on theapplicationelement.
The ViewModel Factory
(docs) The framework does not let you pass your own values to a ViewModel's constructor by default; you supply a ViewModelProvider.Factory that knows how to build it. The viewModelFactory and initializer builder reads the container through APPLICATION_KEY. This replaces the factory that lived inside NotesViewModel in Chapter 5:
(docs) The factory is passed to viewModel(factory = ...). The docs also warn that these factory APIs have changed over the years, so check the current ViewModel documentation if an import or call here does not compile.
Testing Gets Easy
(docs) The guides say dependency injection lets you swap implementations, passing fakes or mocks to a ViewModel under test, and the Dagger guide shows exactly this: constructing the ViewModel directly with a fake repository and no DI framework. That is the payoff of everything since Chapter 5: the test above needs no container at all.
FakeSettingsRepository only exists if SettingsRepository is an interface; Exercise 3 asks you to extract it.
What Manual DI Costs
| Cost | Where you feel it |
|---|---|
| Boilerplate | Every new ViewModel needs a line in the factory; every new dependency a property in the container (general knowledge) |
| You manage the container yourself | (docs) The guide notes you create instances for all dependencies by hand and manage them yourself |
| Lifetimes are your problem | Which objects live for the whole app, which for one screen, is something you decide and enforce by hand (general knowledge) |
| Wiring mistakes show up late | A wrongly built object fails when it is first used, not when the app is built (general knowledge) |
(docs) For a small app this is fine; the recommendations name manual DI and Hilt as the two options for simple apps. As the number of classes grows, the container and factory grow with it, and that is the problem Hilt solves. Seeing the hand-written version first means that when Chapter 10 generates it for you, you will know what it is generating.
Try It Yourself
Create AppContainer and DefaultAppContainer, change NotesApp, add AppViewModelProvider, and remove the old factory and NetworkModule. Run the app and confirm nothing visible changed. Report any build errors, especially from the factory imports.
Add a TimeProvider that DefaultNotesRepository uses for createdAt, supply it from the container, and write a test that proves a new note gets a fixed time. Say what you gained over calling System.currentTimeMillis() directly.
Extract an interface from SettingsRepository, add a fake, and write the ViewModel test from the chapter. Then write a FakeAppContainer that supplies both fakes, and say where in the app it could be used.
AppContainer on Application; managing it yourself; the factory requirement and ViewModelProvider.Factory; the viewModelFactory and initializer builder with APPLICATION_KEY; viewModel(factory = ...); constructor injection; testing with fakes or mocks; manual DI or Hilt for simple apps; Hilt generating the factory; the warning that some pages are old and the APIs have changed.General knowledge, not checked: the code and imports as written; the four problems list;
by lazy giving one instance; lifetimes and late wiring failures; the TimeProvider example.Not verified: every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Manual dependency injection (developer.android.com), Create ViewModels with dependencies (developer.android.com), Add repository and Manual DI codelab (developer.android.com), Recommendations for Android architecture (developer.android.com), Using Dagger in Android apps (developer.android.com).