Junior — Middle
What tools or libraries for Dependency Injection have you used in your projects?
sobes.tech AI
Answer from AI
In Android projects, the following dependency injection libraries are commonly used:
- Dagger 2 — a static, compile-time DI framework from Google that generates code during compilation, ensuring high performance.
- Hilt — a wrapper over Dagger 2 that simplifies its usage and integration with Android components.
- Koin — a lightweight Kotlin DI framework that does not require code generation and is easier to set up, suitable for small to medium projects.
Example of using Koin:
// Define a module
val appModule = module {
single { Repository() }
factory { ViewModel(get()) }
}
// Initialize Koin in Application
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@App)
modules(appModule)
}
}
}
// Inject into Activity
class MainActivity : AppCompatActivity() {
private val viewModel: ViewModel by inject()
}
The choice of tool depends on project requirements and team preferences.