Junior — Middle
Can you list the main components and concepts used in Dagger for dependency injection?
sobes.tech AI
Answer from AI
Main components and concepts of Dagger for dependency injection:
- @Component — an interface that connects modules and injection points. It generates code to provide objects.
- @Module — a class that contains methods annotated with
@Provides, describing how to create dependencies. - @Provides — an annotation for methods inside a module that return dependency objects.
- @Inject — an annotation indicating where dependencies should be injected (constructors, fields, methods).
- Scope — annotations like
@Singletonthat define the lifetime scope of objects.
Example:
@Module
class NetworkModule {
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient();
}
}
@Component(modules = NetworkModule.class)
interface AppComponent {
void inject(MainActivity activity);
}
Dagger generates an implementation of AppComponent that can create and inject dependencies defined in modules.