Junior — Middle
What are the main elements and principles of Dagger in the context of dependency injection?
sobes.tech AI
Answer from AI
Dagger is a dependency injection library for Android that helps manage the creation and provision of objects.
Main elements of Dagger:
- @Component — an interface that connects dependency providers (modules) with consumers.
- @Module — a class containing methods annotated with @Provides that create and supply dependencies.
- @Inject — an annotation used to indicate points of dependency injection (e.g., constructors, fields).
Working principle:
- Modules describe how to create objects.
- The component assembles these modules and provides dependencies.
- In usage points (e.g., in Activity or ViewModel), Dagger automatically injects the required objects using @Inject.
Example:
@Module
class NetworkModule {
@Provides
fun provideApiService(): ApiService {
return Retrofit.Builder()...build().create(ApiService::class.java)
}
}
@Component(modules = [NetworkModule::class])
interface AppComponent {
fun inject(activity: MainActivity)
}
class MainActivity : AppCompatActivity() {
@Inject lateinit var apiService: ApiService
override fun onCreate(savedInstanceState: Bundle?) {
DaggerAppComponent.create().inject(this)
super.onCreate(savedInstanceState)
// apiService is ready to use
}
}