Dagger 2 is a powerful dependency injection framework for Java and Android that helps manage your application's dependencies in a clean and efficient way. Here's a basic overview of how to integrate Dagger 2 into your Android app.
First, you need to add the Dagger 2 dependencies to your app's build.gradle
file:
dependencies {
implementation 'com.google.dagger:dagger:2.x' // Replace x with the latest version
kapt 'com.google.dagger:dagger-compiler:2.x' // For Kotlin projects
}
Modules are classes where you define methods that provide dependencies.
@Module
class AppModule {
@Provides
fun provideContext(application: Application): Context {
return application.applicationContext
}
@Provides
fun provideNetworkService(): NetworkService {
return NetworkService()
}
}
Components are interfaces that connect the modules and the classes that need dependencies.
@Component(modules = [AppModule::class])
interface AppComponent {
fun inject(application: MyApplication)
fun inject(activity: MainActivity)
}
Initialize the Dagger component in your Application class:
class MyApplication : Application() {
lateinit var appComponent: AppComponent
override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent.builder()
.appModule(AppModule())
.build()
}
}
Finally, you can inject dependencies into your activities or fragments:
class MainActivity : AppCompatActivity() {
@Inject lateinit var networkService: NetworkService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as MyApplication).appComponent.inject(this)
// Now you can use networkService
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?