Dagger 2.11 [dagger.android.AndroidInjector.inject(T)]找到一个依赖循环

时间:2017-09-30 06:48:42

标签: android dagger-2 dagger

我是Dagger的新手,在Android应用程序中学习Dagger 2.11的实现。我按照一些教程编写了一个示例项目。但是我收到了这个错误:

Error:(19, 8) error: [dagger.android.AndroidInjector.inject(T)] Found a dependency cycle:
com.saharan.daggerart.DaggerArtApplication is injected at
com.saharan.daggerart.AppModule.provideApplicationContext(application)
com.saharan.daggerart.DaggerArtApplication is injected at
com.saharan.daggerart.AppModule.provideSharedPreferences(application)
android.content.SharedPreferences is injected at
com.saharan.daggerart.MainActivity.preferences
com.saharan.daggerart.MainActivity is injected at
dagger.android.AndroidInjector.inject(arg0)

AppComponent:

 @Singleton
@Component(modules = {AndroidInjectionModule.class, AppModule.class, ActivityModule.class})
public interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);
        AppComponent build();
    }
    void inject(DaggerArtApplication application);
}

的AppModule:

@Singleton
@Module(subcomponents = {MainActivityComponent.class})
public class AppModule {

    @Provides
    @Singleton
    DaggerArtApplication provideApplicationContext(DaggerArtApplication application) {
        return application;
    }

    @Provides
    @Singleton
    SharedPreferences provideSharedPreferences(DaggerArtApplication application) {
        return application.getSharedPreferences(Constants.PrefKeys.PREF_NAME, Context.MODE_PRIVATE);
    }
}

ActivityModule:

@Module
public abstract class ActivityModule {
    @Binds
    @IntoMap
    @ActivityKey(MainActivity.class)
    abstract AndroidInjector.Factory<? extends Activity> bindMainActivity(MainActivityComponent.Builder builder);
}

MainActivityComponent:

@Subcomponent(modules = MainActivityModule.class)
public interface MainActivityComponent extends AndroidInjector<MainActivity> {
    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<MainActivity> {
    }
}

MainActivityModule:

@Module
public class MainActivityModule {

    @Provides
    String provideUserName() {
        return "Mr. Bond";
    }
}

现在的MainActivity:

 public class MainActivity extends AppCompatActivity {

    @Inject String username;
    @Inject
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidInjection.inject(this);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

我做错了什么? 请帮忙!!

1 个答案:

答案 0 :(得分:3)

看起来像是一个错字。

DaggerArtApplication provideApplicationContext(DaggerArtApplication application)

这意味着Dagger需要DaggerArtApplication来提供DaggerArtApplication。我猜你想说

DaggerArtApplication provideApplicationContext(Application application)

DaggerArtApplication绑定到Application