Skip to content Skip to sidebar Skip to footer

Presenter Injection With Dagger 2

I just started using Dagger 2 and I found online thousands guides each one with a different implementation and I'm a bit confused now. So basically this is what I wrote at the mome

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Presenter Injection With Dagger 2"