Sobes.tech
Junior — Middle

How can automatic dependency injection be configured when using Dagger?

sobes.tech AI

Answer from AI

To set up automatic dependency injection in Dagger, you need to use the @Inject annotations and @Component interfaces.

  1. In the constructor of the class that should receive dependencies, the @Inject annotation is placed.

  2. An interface with the @Component annotation is created, which links dependency providers (modules) and the classes into which they will be injected.

  3. In the class where injection is needed, the component's inject(this) method is called, which automatically injects all dependencies marked with @Inject.

Example:

class Engine {
    @Inject
    Engine() {}
}

class Car {
    @Inject
    Engine engine;

    @Inject
    Car() {}
}

@Component
interface CarComponent {
    void inject(MainActivity activity);
}

// In MainActivity
CarComponent component = DaggerCarComponent.create();
component.inject(this); // dependencies will be injected automatically

Thus, Dagger generates code that automatically creates and injects dependencies if annotations and components are used correctly.