Dagger 2, a dependency injection framework for Android, simplifies dependency management, resulting in testable, maintainable code. The article outlines Dagger 2 implementation, including component and module creation, dependency scopes, and testing
Dagger 2 is a widely popular dependency injection framework for Android development. It allows developers to manage dependencies and create lightweight, testable, and maintainable code.
To use Dagger 2 in your Android app, you need to follow these steps:
Add the Dagger 2 library to your project's build.gradle file:
dependencies { implementation 'com.google.dagger:dagger:2.38.1' annotationProcessor 'com.google.dagger:dagger-compiler:2.38.1' }
Create a component interface:
@Component interface AppComponent { fun inject(activity: MainActivity) // Members to inject }
Create a module to provide the dependencies:
@Module class AppModule { @Provides fun provideRepository(): Repository { return RepositoryImpl() // Assuming RepositoryImpl implements Repository } }
Initialize the component in your application class:
class MyApplication : Application() { private val appComponent: AppComponent by lazy { DaggerAppComponent.builder().appModule(AppModule()).build() } override fun onCreate() { super.onCreate() appComponent.inject(this) // Inject the application instance into the component } }
Dagger 2 offers different scopes to control the lifetime of injected dependencies:
To test your dependency hierarchy, you can use the following approaches:
The above is the detailed content of Getting started with Dagger2. For more information, please follow other related articles on the PHP Chinese website!