A fast dependency injection framework for Android and Java.
Apache-2.0
Quick Start
Maven Coordinates
com.google.dagger:daggerSetup Steps
- Add the Dagger dependency to your build.gradle file using the latest version from the repository.
- Annotate your classes with @Inject to specify dependencies.
- Create a @Component interface to define the injection graph.
- Build your project to generate the necessary Dagger code.
Overview
Dagger is a compile-time dependency injection framework that generates code to manage dependencies in Android and Java applications. It enhances performance by reducing reflection and provides compile-time validation to catch errors early.
Features
✓Compile-time code generation for efficiency
✓Reduces boilerplate code in dependency management
✓Improves testability by facilitating mock injection
✓Provides scope management for lifecycle-aware dependencies
Use Cases
●Managing complex dependency graphs in large-scale Android apps
●Injecting dependencies into activities, fragments, and services
●Scoping dependencies to application or activity lifecycles
When Not to Use
✗Small projects with minimal dependencies where setup overhead may not be justified
✗When using Hilt, which simplifies Dagger for Android
✗If preferring runtime dependency injection for simpler setups
Usage Examples
Basic Field Injection
@Inject lateinit var userRepository: UserRepositoryInject a dependency directly into a class field.
Component Interface
@Component interface AppComponent { fun inject(activity: MainActivity) }Define a component to provide dependencies for injection.
Common Pitfalls
- Circular dependencies can cause compilation errors
- Forgetting to provide necessary @Module or @Bindings
- Incorrect scoping leading to memory leaks or unintended instance sharing
Integration
Works well with
Hilt (built on Dagger for Android)Retrofit for network callsRoom for database access
- Ensure proper module setup in multi-module projects
- Use @Subcomponent for nested or feature-specific dependency graphs
Alternatives
Hilt
Simplifies Dagger setup for Android with pre-defined components and reduced boilerplate.
Koin
A pure Kotlin dependency injection framework with a more declarative and lightweight approach.