Presenter injection with Dagger 2

只愿长相守 提交于 2019-12-03 06:12:17
David Medenjak

You are mixing thing up. To provide your presenter, you should switch to something like the following:

Use constructor injection if possible. It will make things much easier

public class HomePresenterImpl {

    @Inject
    public HomePresenterImpl(NetworkService networkService) {
        // ...
    }

}

To provide the interface use this constructor injection and depend on the implementation:

Presenter<FwView> provideHomePresenter(HomePresenterImpl homePresenter) {
    return homePresenter;
}

This way you don't have to call any constructors yourself. And to actually inject the presenter...

public class MyFragment extends Fragment {

    @Inject
    Presenter<FwView> mHomePresenter;

    public void onCreate(Bundle xxx) {
        // simplified. Add your modules / Singleton component
        PresenterComponent component = DaggerPresenterComponent.create().inject(this);
    }
}

This way you will inject the things. Please read this carefully and try to understand it. This will fix your major problems, you still can not provide 2 presenters of the same type from the same module (in the same scope)

// DON'T
@Provides
Presenter<FwView> provideHomePresenter(NetworkService networkService) { /**/ }

@Provides
Presenter<FwView> provideSearchPresenter(NetworkService networkService) { /**/ }

This will not work. You can not provide 2 objects of the same kind. They are indistinguishable. Have a look at @Qualifiers like @Named if you are sure this is the way you want to go.

You do not have to provide Presenter if @Inject annotation is used in the constructor. @Inject annotation used in the constructor of the class makes that class a part of dependencies graph. So, it also can be injected when needed.

On the other hand, if you add @Inject annotation to fields, but not to constructors, you have to provide that class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!