Search code examples
dagger-2android-mvp

Constructor injecting make MissingBinding in dagger 2 and mvp


I have created simple project with dagger2 and mvp.

This is my component :

@MainScope
@Component(modules = {MainModule.class})
public interface IMainComponent {
    void inject(MainActivity mainActivity);
}

and This is MainModule.class:

@Module
public class MainModule {

    @MainScope
    @Provides
    IMain.IMainModel model() {
        return new MainModel();
    }
}

Now in presenter i want to inject presenter from it's constructor so i do :

public class MainPresenter implements IMain.IMainPresenter {
    IMain.IMainModel model;
    IMain.IMainView view;

    @Inject
    public MainPresenter(IMain.IMainModel model) {
        this.model = model;
    }  

But i got This error:

  symbol:   class DaggerIMainComponent
  location: package com.safarayaneh.engineer.main.di
E:\Projects\Android\NewEng\Engineer\engineer\src\main\java\com\safarayaneh\engineer\main\di\IMainComponent.java:9: error: [Dagger/MissingBinding] com.safarayaneh.engineer.main.mvp.IMain.IMainPresenter cannot be provided without an @Provides-annotated method.

When make provider in MainModule.class to create presenter and remove @Inject above presenter constructor , everything is fine: @Module

public class MainModule {

    @MainScope
    @Provides
    IMain.IMainModel model() {
        return new MainModel();
    }


    @MainScope
    @Provides
    IMain.IMainPresenter presenter(IMain.IMainModel model) {
        return new MainPresenter(model);
    }
}

Solution

  • Your problem is that your Activity expects IMain.IMainPresenter, but if you just annotate the constructor then what's placed on the objects graph is the concrete MainPresenter.

    You've got three options here:

    1. Use explicit provider method (as you did)
    2. Use @Binds annotation inside the module to specify that MainPresenter should be provided as IMain.IMainPresenter
    3. Don't use interface for the presenter