I am trying to understand Dagger 2, I have researched it in several articles and examples on Gibhub, but still don't understand why there are constructor injections in the presenters. For example, in order to make a field injection in the TaskActivity we make:
DaggerTasksComponent.builder()
.tasksRepositoryComponent(((ToDoApplication) getApplication()).getTasksRepositoryComponent())
.tasksPresenterModule(new TasksPresenterModule(tasksFragment)).build()
.inject(this);
and with that, we inject:
@Inject TasksPresenter mTasksPresenter;
I thought these lines of code were enough to create a TaskPresenter object. But when I go to TaskPresenter I see the following lines.
@Inject
TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
mTasksRepository = tasksRepository;
mTasksView = tasksView;
}
This is what I don't understand. According to this example(https://github.com/CasterIO/simplemvp) there is no such constructor injection in the Presenter.
Thanks in advance.
We can provide dependencies in two ways :
@Provides
TasksPresenter provide TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
return new TasksPresenter(tasksRepository,tasksView);
}
@Inject
TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
mTasksRepository = tasksRepository;
mTasksView = tasksView;
}
One thing to observe here is Consrtuctor Injection solve two thing
So in https://github.com/CasterIO/simplemvp example they might be using first approach.
Thanks for the answer!
@cahegi we can use constructor Injection when the class is defined by our self like in this case TasksPresenter
Most helpful comment
@cahegi we can use constructor Injection when the class is defined by our self like in this case TasksPresenter