我有這樣的模塊: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