【发布时间】:2016-07-06 14:22:24
【问题描述】:
我有这个模块:
@Module
public class MainModule {
private Context context;
public MainModule(Context context) {
this.context = context;
}
@Provides
@Singleton
Dao providesDao() {
return new Dao();
}
@Provides
@Singleton
FirstController providesFirstController(Dao dao) {
return new FirstController(dao);
}
@Provides
@Singleton
SecondController providesSecondController(Dao dao) {
return new SecondController(dao);
}
}
还有这个组件:
@Singleton
@Component(modules = MainModule.class)
public interface MainComponent {
void inject(FirstView view);
void inject(SecondView view);
}
最后是注入器类,它在App.onCreate() 方法中初始化:
public enum Injector {
INSTANCE;
MainComponent mainComponent;
public void initialize(App app) {
mainComponent = DaggerMainComponent.builder()
.mainModule(new MainModule(app))
.build();
}
public MainComponent getMainComponent() {
return mainComponent;
}
}
在我的 FirstView 和 SecondView(即Fragments)中,我有这个:
@Inject
FirstController controller; //and SecondController for the second view
@Override
public void onAttach(Context context) {
super.onAttach(context);
Injector.INSTANCE.getMainComponent().inject(this);
}
在第一个片段中,一切正常,控制器被注入。但在第二种观点中它不是:只是返回null。
我在“provides”模块的方法中设置了断点,providesFirstController 被执行但providesSecondController 没有被执行。
我做错了什么?我是 Dagger2 的新手,所以任何建议都将不胜感激。
【问题讨论】:
-
你在哪里打电话
initialize(App app)? -
在
App.onCreate()方法中。 App 是我扩展 Application 的类 -
在片段的构造函数中调用
inject() -
它不起作用:(
-
请分享您的 MainModule.java 。