Dagger Fundamentals & Manual DI Flashcards
ARCHITECTURE › Dependency Injection
- What does @Inject on a constructor tell Dagger?
- It tells Dagger how to create instances of that class and what its constructor dependencies are. Dagger generates a factory for the type and can satisfy it wherever it appears in the graph.
- What is a @Component and what does Dagger generate from it?
- An interface that defines a dependency graph. Dagger generates an implementation (e.g. DaggerApplicationGraph) plus factory classes for every type, exposing the provision methods you declared.
- When do you need @Module and @Provides instead of @Inject?
- When you can't annotate the constructor: interfaces, classes you don't own (e.g. Retrofit, OkHttp), or types needing custom construction. A @Provides method in a @Module tells Dagger how to build that type.
- @Binds vs @Provides?
- @Binds is an abstract method that maps an interface to its implementation; Dagger needs no generated body, so it's more efficient. @Provides is a concrete method holding real construction logic. Use @Binds for simple interface-to-impl bindings.
- What problem do qualifiers solve in Dagger?
- They disambiguate multiple bindings of the same type. Without one, two String or OkHttpClient bindings collide. A @Qualifier annotation (or built-in @Named) tags each binding so Dagger picks the right one at the injection site.
- What is the role of scopes and @Subcomponent?
- A scope (e.g. @Singleton) binds an instance's lifetime to its component so the same instance is reused. Subcomponents create child graphs for specific flows that inherit the parent graph and can be released to free objects when the flow ends.
- Why is compile-time DI an advantage of Dagger over reflection-based or runtime DI?
- Dagger walks the graph at build time, verifying every dependency is satisfiable and that no cycles exist, so missing bindings fail compilation, not at runtime. No reflection means it's faster and traceable, since generated code mirrors hand-written wiring.
- How do you do dependency injection manually without a framework?
- Pass dependencies through constructors (constructor injection) and centralize shared instances in an AppContainer held by the Application. Use flow containers (e.g. LoginContainer) created and destroyed per feature flow to scope shorter-lived objects.
- Hilt/Dagger vs Koin: the core tradeoff?
- Hilt/Dagger generate and validate the graph at compile time, so wiring errors surface at build. Koin is a runtime DSL service locator: simpler setup and faster builds, but missing or misconfigured dependencies throw only at runtime when resolved.