Android Dagger2 2.11 unscoped Appcomponent引用范围绑定

时间:2017-09-25 19:55:39

标签: java android dagger-2

我使用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。重建项目后,我收到错误

enter image description here 如果我通过provideSharedPreferences删除注释@Singleton,则项目重建正确。 为什么问题@Singleton注释由provideSharedPreferences?

1 个答案:

答案 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);
    }