ошибка: [dagger.android.AndroidInjector.inject (T)] Обнаружен цикл зависимости - PullRequest
0 голосов
/ 11 мая 2018

Может кто-нибудь сказать мне, почему эта ошибка показывает.Я много пробовал некоторые сообщения от stackoverflow, но не могу определить.Борюсь с этой ошибкой на весь день.до кинжала 2.11 все работало нормально.после обновления до 2.11 появляется ошибка.

        E:\studio projects\MVP-Login\app\build\tmp\kapt3\stubs\debug\com\example\anbu\mvpkotlin\di\component\AppComponent.java:8: error: [dagger.android.AndroidInjector.inject(T)] Found a dependency cycle:
public abstract interface AppComponent {
            ^
  com.example.anbu.mvpkotlin.data.network.NccApi is injected at
      com.example.anbu.mvpkotlin.di.modules.AppModules.provideAPI$app_debug(apiManager)
  com.example.anbu.mvpkotlin.data.network.NccApi is injected at
      com.example.anbu.mvpkotlin.ui.accounts.interactor.AccountInteractor.<init>(…, api)
  com.example.anbu.mvpkotlin.ui.accounts.interactor.AccountInteractor is injected at
      com.example.anbu.mvpkotlin.ui.accounts.AccountModule.provideAccountInteractor$app_debug(accountInteractor)
  com.example.anbu.mvpkotlin.ui.accounts.interactor.AccountInteractorContract is injected at
      com.example.anbu.mvpkotlin.ui.accounts.presenter.AccountPresenter.<init>(interactor, …)
  com.example.anbu.mvpkotlin.ui.accounts.presenter.AccountPresenter<com.example.anbu.mvpkotlin.ui.accounts.view.AccountViewContract,com.example.anbu.mvpkotlin.ui.accounts.interactor.AccountInteractorContract> is injected at
      com.example.anbu.mvpkotlin.ui.accounts.AccountModule.provideAccountPresenter$app_debug(accountPresenter)
  com.example.anbu.mvpkotlin.ui.accounts.presenter.AccountPresenterContract<com.example.anbu.mvpkotlin.ui.accounts.view.AccountViewContract,com.example.anbu.mvpkotlin.ui.accounts.interactor.AccountInteractorContract> is injected at
      com.example.anbu.mvpkotlin.ui.accounts.view.AccountActivity.presenter
  com.example.anbu.mvpkotlin.ui.accounts.view.AccountActivity is injected at
      dagger.android.AndroidInjector.inject(arg0)

Вот мой класс AppComponent, который я добавил в свой проект.Это не совсем абстрактно, как показывает ошибка.

    @Singleton
@Component(modules = [(AndroidInjectionModule::class), (ActivityBuilder::class),
    (AppModules::class)])
interface AppComponent {

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent
    }

    fun inject(app: MyApplication)

}

А вот класс Application Module, который я добавил в свой проект.

@Module
class AppModules {

@Provides
@Singleton
internal fun provideContext(application: Application): Context = application

@Provides
@PreferenceInfo
internal fun providePrefName(): String = AppConstants.PREF_NAME

@Provides
@Singleton
internal fun providePreference(prefManager: PrefManager): 
PrefManagerContract = prefManager

@Provides
@Singleton
internal fun provideAppDatabase(context: Context): NccDatabase =
        Room.databaseBuilder(context, NccDatabase::class.java, "****")
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build()

@Provides
internal fun provideCompositeDisposable(): CompositeDisposable = 
CompositeDisposable()

@Provides
@Singleton
internal fun provideAPI(apiManager: NccApi): NccApi = apiManager

@Provides
internal fun provideSchedulerProvider(): SchedulerProvider = 
SchedulerProvider()

/*@Provides
@Singleton
internal fun providerTokenManager(): TokenManager = TokenManager()*/

Это мой класс AccountModule

            @Module
    class AccountModule {

        @Provides
        internal fun provideAccountInteractor(accountInteractor: AccountInteractor): AccountInteractorContract = accountInteractor

        @Provides
        internal fun provideAccountPresenter(accountPresenter: AccountPresenter<AccountViewContract, AccountInteractorContract>)
                : AccountPresenterContract<AccountViewContract, AccountInteractorContract> = accountPresenter
    }

Вот мой интерфейс веб-служб Retrofit

public interface NccApi {

        Observable<Profile> getProfile(@Url String url, @Header("authorization") String auth);

        @POST
        Call<SigninResponseModel> refreshToken(@Url String url, @Header("authorization") String auth, @Body RefreshTokenRequest body);
    }

Вот мой класс модуля модернизации

        @Module
    class RetrofitModule(internal var mBaseUrl: String) {

    @Provides
    @Singleton
    internal fun provideInterceptor(): okhttp3.Interceptor {
        val interceptorAPI = Interceptor { chain ->
            val original = chain.request()
            var request: Request? = null
            try {
                request = chain.request().newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .method(original.method(), original.body())
                        .build()
            } catch (authFailureError: Exception) {
                authFailureError.printStackTrace()
            }

            val response = chain.proceed(request)

            response
        }
        return interceptorAPI
    }

    @Provides
    @Singleton
    internal fun provideGson(): Gson {
        val gsonBuilder = GsonBuilder()
        return gsonBuilder.create()
    }

    @Provides
    @Singleton
    internal fun provideOkHttpClient(interceptor: Interceptor): OkHttpClient {
        val okHttpBuilder = OkHttpClient.Builder()
        okHttpBuilder.interceptors().add(interceptor)
        val logging = HttpLoggingInterceptor()
        logging.setLevel(HttpLoggingInterceptor.Level.BODY)
        okHttpBuilder.interceptors().add(logging)
        val client = okHttpBuilder.build()
        return client
    }

    @Provides
    @Singleton
    internal fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {
        val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build()
        return retrofit
    }
    }

Вот мой класс приложения

class MyApplication : Application(), HasActivityInjector {

    @Inject
    lateinit internal var activityDispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

    override fun activityInjector() = activityDispatchingAndroidInjector

    override fun onCreate() {
        super.onCreate()

        DaggerAppComponent.builder()
                .application(this)
                .appmodule(AppModules())
                .retrofitModule(RetrofitModule(""))
                .build()
                .inject(this)

    }
    }

1 Ответ

0 голосов
/ 11 мая 2018

Ваш цикл зависимости здесь:

@Provides
@Singleton
internal fun provideAPI(apiManager: NccApi): NccApi = apiManager

Вы зависите от apiManager для предоставления apiManager. У вас должно быть что-то вроде этого здесь:

@Provides
@Singleton
internal fun provideAPI(): NccApi = NccApi()

Выше приведен только пример, суть в том, что вам нужно создать экземпляр API для его предоставления. Или, если у вас есть интерфейс, который реализует ваш apiManager, вы должны вернуть его из метода предоставляет, поэтому вы запрашиваете фактический объект и возвращаете интерфейс. Но, запрашивая реальный объект и возвращая его, вы тут же делаете цикл зависимости.

...