Architecture-samples: Todo-mvp-dagger and constructor injection

Created on 30 Jul 2016  路  3Comments  路  Source: android/architecture-samples

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.

Most helpful comment

@cahegi we can use constructor Injection when the class is defined by our self like in this case TasksPresenter

All 3 comments

We can provide dependencies in two ways :

By Using Provides annotation in module

@Provides
    TasksPresenter provide TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
        return new TasksPresenter(tasksRepository,tasksView);
}

By Using Consrtuctor Injection

 @Inject
    TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
        mTasksRepository = tasksRepository;
        mTasksView = tasksView;
    }

One thing to observe here is Consrtuctor Injection solve two thing

  • Instantiate object
  • Provides the object by adding it in Object graph.

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

spmonk picture spmonk  路  3Comments

BeQuietLee picture BeQuietLee  路  3Comments

johnfrey99 picture johnfrey99  路  7Comments

aballano picture aballano  路  5Comments

AeroEchelon picture AeroEchelon  路  4Comments