如何在@Provides中注入应用程序实例



我的AppModule在编译时崩溃并显示错误:

error: .App cannot be provided without an @Inject constructor or from an @Provides-annotated method.
    public abstract .vcs.IGitHubApi getGitHubApi();
                                                       ^
      .App is injected at
          .AppModule.provideOAuth2Interceptor(app)
      .vcs.OAuth2Interceptor is injected at
          .AppModule.provideOkHttpClient(…, oAuth2Interceptor)
      okhttp3.OkHttpClient is injected at
          .AppModule.provideRetrofit(httpClient, …)
      retrofit2.Retrofit is injected at
          .AppModule.provideGitHubApi(retrofit)
      .vcs.IGitHubApi is provided at
          .AppComponent.getGitHubApi()

这是我AppModule课:

@Module
class AppModule {
    // other providers
    @Singleton
    @Provides
    fun provideOAuth2Interceptor(app: App): OAuth2Interceptor {
        return OAuth2Interceptor(app)
    }
}

AppComponent

@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
    // other methods
    fun inject(app: App)
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun context(context: Context): Builder
        fun build(): AppComponent
    }
}

还有我初始化AppComponentApp类:

class App: Application() {
    override fun onCreate() {
        super.onCreate()
        DaggerAppComponent.builder()
            .context(this)
            .build()
            .inject(this)
    }
}

我知道dagger找不到App来构建provideOAuth2Interceptor但我不知道如何在提供程序中注入App

附言我还在学习dagger

在 AppComponent 中,应绑定 App 类的实例,使其成为 Dagger 图的一部分。

@Component.Builder
    interface Builder {
        @BindsInstance
        fun context(context: Context): Builder
        @BindsInstance
        fun application(app: App): Builder
        fun build(): AppComponent
    }

并在您的 App 类中,在构造时向组件提供 App 的实例-

DaggerAppComponent.builder()
    .context(this)
    .application(this)
    .build()
    .inject(this)

最新更新