Dagger
01 / 02

Dagger: Scoping, Android Lifecycle & When to Adopt It

Dagger: Scoping, Android Lifecycle & When to Adopt It

Why Compile-Time Errors Matter

A missing @Provides method fails the BUILD with a clear message pointing at exactly what's missing -- far cheaper to fix than the same misconfiguration silently resolving to null and causing a confusing NullPointerException deep in production, far removed from its actual root cause.

Scoped Components & Android's Lifecycle

Android's OS-managed Activity/Fragment lifecycle (recreated on rotation, not created by application code) makes manual dependency management awkward. Multiple, differently-scoped Components (often parent-child) let a dependency's actual lifetime match its scope -- an app-wide singleton lives in a root Component, a screen-scoped dependency lives in a child Component tied to that screen.

Dagger vs. Hilt

Hilt is built directly on Dagger's compile-time code generation, but standardizes around common Android patterns (injecting into Activities/Fragments/ViewModels), reducing the manual Component/Module boilerplate plain Dagger requires -- Google's recommended default for new Android projects.

Constructor Injection Aids Testing

// Tests bypass Dagger's generated wiring entirely -- constructor
// injection is what makes this substitution possible
val repo = UserRepository(mockApiClient)

Why DI Over a Service Locator

class UserRepository(apiClient: ApiClient, cache: Cache) makes dependencies visible right in the constructor signature. A class internally calling ServiceLocator.get(ApiClient::class) buried in a method hides that same dependency, requiring a reader to trace the implementation to discover what it actually needs.

When Dagger Is (and Isn't) Worth It

A small, few-class utility app can reasonably construct dependencies manually. As an application's dependency graph grows, manual wiring becomes increasingly tedious and error-prone -- Dagger's automation scales without that same linear (or worse) manual burden, which is typically the point teams find the setup cost clearly worth it.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free