dagger-2 - 构造函数注入使 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);
}
}
解决方案
您的问题是您的 Activity 期望IMain.IMainPresenter
,但是如果您只是注释构造函数,那么放置在对象图上的是具体的MainPresenter
。
你在这里有三个选择:
- 使用显式提供程序方法(就像您所做的那样)
- 在模块内使用
@Binds
注释来指定MainPresenter
应该作为IMain.IMainPresenter
- 不要为演示者使用界面
推荐阅读
- string - 如何将字符向量中的字符附加到C++中的字符串?
- node.js - Heroku 在导入“aws-sdk”时崩溃
- python - 在 FLASK 中存储没有 COOKIES 的持久 HTTP 连接的变量
- node.js - 将 wait-for-it.sh 与 docker 一起使用时启动数据包不完整
- c# - 如何避免在Unity中翻转附加到主相机的对象
- r - 如何使用ggplot在收益率曲线上绘制脉冲响应?
- python - 键绑定导致功能在启动时自动运行
- c# - ASP.Net Azure SignalR 错误无法 ping 服务器。服务器响应状态码 401,停止连接
- arrays - Rust 中的耦合数组
- node.js - 我们在 django 中是否有一些包或模块,通过它我们可以在编辑代码时看到 django 中 html 文件的实时更改?