如何在@Provides 中注入Application 实例?

How to inject Application instance in @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 class:

@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
    }
}

还有我的 App class 我初始化的地方 AppComponent:

class App: Application() {

    override fun onCreate() {
        super.onCreate()

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

我知道 Dagger 找不到 App 来构建 provideOAuth2Interceptor 但我不知道如何将 App 注入提供商。

P.S.还在学习匕首

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

@Component.Builder
    interface Builder {
        @BindsInstance
        fun context(context: Context): Builder

        @BindsInstance
        fun application(app: App): Builder

        fun build(): AppComponent
    }

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

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