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

时间:2019-06-06 20:04:44

标签: android kotlin dagger-2

我的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
    }
}

还有我的App类,我在其中初始化AppComponent

class App: Application() {

    override fun onCreate() {
        super.onCreate()

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

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

PS 。我仍在学习 Dagger

1 个答案:

答案 0 :(得分:1)

在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)