Junior — Middle
What is the difference between components and modules in Dagger?
sobes.tech AI
Answer from AI
In Dagger, modules are classes that provide dependencies through methods annotated with @Provides. They describe how to create the objects needed for injection.
Components are interfaces that connect dependency providers (modules) with injection points (such as fields or constructors). The component is responsible for creating and supplying the objects defined in the modules and managing their lifecycle.
In simpler terms:
- A module is a factory that knows how to create dependencies.
- A component is a bridge between modules and classes where these dependencies are injected.
Example:
@Module
class NetworkModule {
@Provides
Retrofit provideRetrofit() {
return new Retrofit.Builder().baseUrl("https://api.example.com").build();
}
}
@Component(modules = NetworkModule.class)
interface AppComponent {
void inject(MainActivity activity);
}