T
T
Tsuzukeru2021-03-08 15:44:28
Android
Tsuzukeru, 2021-03-08 15:44:28

Why do you need to inject dependencies into an Activity using a Component?

At the very beginning of studying DI and Dagger, questions arise that I cannot find an answer to.
There is a Car class that has two references to Engine and Wheels.

public class Car {
    private static final String TAG = "Car";
    @Inject Engine engine;
    private Wheels wheels;

    @Inject
    Car(Wheels wheels){
        this.wheels = wheels;
    }

    public void drive(){
        Log.d(TAG, "driving...");
    }
}


public class Engine {

    @Inject
    public Engine() {
    }
}


public class Wheels {

    @Inject
    public Wheels() {
    }
}

Code Component
@Component
public interface CarComponent {
    void inject(MainActivity mainActivity);
}


Activity code
public class MainActivity extends AppCompatActivity {
   @Inject Car car;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CarComponent component = DaggerCarComponent.create();
        component.inject(this);
        car.drive();
    }
}


Tell me why I can use @Inject to inject an Engine into a Car, but at the same time I can’t inject a Car into an Activity in the same way (I need to do this through a Component)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2021-03-08
@Tsuzukeru

Because the dagger needs an entry point. For android, this is in most cases an activity or a fragment

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question