我有这样的模块:Dagger2不注入字段
@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(即Fragment
s)中,我有这个:
@Inject
FirstController controller; //and SecondController for the second view
@Override
public void onAttach(Context context) {
super.onAttach(context);
Injector.INSTANCE.getMainComponent().inject(this);
}
在第一个片段中,一切正常,控制器被注入。但在第二种观点中,它不是:仅返回null
。
我已经在“提供”模块的方法中放置了断点,并且执行了providesFirstController
而不是providesSecondController
。
我在做什么错?我是Dagger2的新手,所以任何建议将不胜感激。
你在哪里调用'initialize(App app)'? – znat
在'App.onCreate()'方法中。应用程序是我的类扩展应用程序 –
在片段的构造函数调用'inject()' – EpicPandaForce