我使用https://medium.com/@iammert/new-android-injector-with-dagger-2-part-1-8baa60152abe的dagger2演示。我已将SharedPreferences添加到我的AppModule.java
@Module(subcomponents = {
MainActivityComponent.class,
DetailActivityComponent.class,
Detail2ActivityComponent.class})
public class AppModule {
@Provides
@Singleton
Context provideContext(Application application) {
return application;
}
@Provides
@Singleton //if i remove dagger works right
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
}
我在MainActivity中注入SharedPreferences。重建项目后,我收到错误
如果我通过provideSharedPreferences删除注释@Singleton,则项目重建正确。 为什么问题@Singleton注释由provideSharedPreferences?
答案 0 :(得分:6)
您需要将@Singleton添加到AppComponent类:
@Singleton // <---- Add this line
@Component(modules = {
AndroidInjectionModule.class,
AppModule.class,
ActivityBuilder.class})
public interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance Builder application(Application application);
AppComponent build();
}
void inject(AndroidSampleApp app);
}