Junior — Middle
What is the role of modules in Dagger and why are they necessary for dependency injection?
sobes.tech AI
Answer from AI
Modules in Dagger serve to provide dependencies that cannot or are inconvenient to create automatically through constructors. They contain methods annotated with @Provides, which describe how to create a specific object. This allows centralized management of dependency creation and configuration, for example, objects with non-standard constructors or those requiring parameters.
Without modules, Dagger would not know how to create certain types of objects, especially if they lack annotated constructors or require complex creation logic.
Example of a module:
@Module
public class NetworkModule {
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.build();
}
}