Junior — Middle
To which principle of SOLID does the use of Dagger for dependency injection relate?
sobes.tech AI
Answer from AI
Using Dagger for dependency injection relates to the Dependency Inversion Principle (D) from SOLID.
This principle states that:
- High-level modules should not depend on low-level modules directly.
- Both should depend on abstractions.
- Abstractions should not depend on details; details should depend on abstractions.
Dagger helps implement this principle by providing a mechanism for automatic dependency injection through abstractions (interfaces or abstract classes), reducing coupling and increasing testability and flexibility.
Example of using Dagger:
@Component
interface AppComponent {
void inject(MyActivity activity);
}
class MyActivity {
@Inject
MyRepository repository;
void onCreate() {
DaggerAppComponent.create().inject(this);
repository.loadData();
}
}
Here, MyActivity does not create MyRepository directly but receives it via dependency injection, which aligns with the Dependency Inversion principle.