首页 > 解决方案 > 构造函数注入使 Dagger 2 和 mvp 中的 MissingBinding

问题描述

我用 dagger2 和 mvp 创建了一个简单的项目。

这是我的组件:

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

这是 MainModule.class:

@Module
public class MainModule {

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

现在在演示者中,我想从它的构造函数中注入演示者,所以我这样做:

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

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

但我得到了这个错误:

  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.

provider在 MainModule.class 中创建演示者并删除@Inject上面的演示者构造函数时,一切都很好:@Module

public class MainModule {

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


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

标签: dagger-2android-mvp

解决方案


您的问题是您的 Activity 期望IMain.IMainPresenter,但是如果您只是注释构造函数,那么放置在对象图上的是具体的MainPresenter

你在这里有三个选择:

  1. 使用显式提供程序方法(就像您所做的那样)
  2. 在模块内使用@Binds注释来指定MainPresenter应该作为IMain.IMainPresenter
  3. 不要为演示者使用界面

推荐阅读