【问题标题】:Handle multiple retrofit client using dagger hilt as dependency injection?使用匕首柄作为依赖注入来处理多个改造客户端?
【发布时间】:2021-10-10 11:02:01
【问题描述】:

我想在我的 android 应用程序中使用两个不同的后端以不同的响应格式,我使用 hilt 作为依赖注入和网络调用的改造,这非常适合工作。

因为我已经添加了我的第二个服务器网络文件并在应用程序模块中,它给了我最后列出的错误。

我需要知道在这种情况下不做任何显着架构更改的出路。

@Keep
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideRetrofit(gson: Gson,@ApplicationContext appContext: Context): Retrofit = Retrofit.Builder()
    .client(
        OkHttpClient().newBuilder()
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).readTimeout(80,TimeUnit.SECONDS)
            .addInterceptor(
                ChuckerInterceptor.Builder(appContext)
                    .collector(ChuckerCollector(appContext))
                    .maxContentLength(250000L)
                    .redactHeaders(emptySet())
                    .alwaysReadResponseBody(false)
                    .build()
            )
            .build()
    )
    .baseUrl(UtilSingleton.instance!!.GetBaseUrl())
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build()

@Provides
fun provideGson(): Gson = GsonBuilder().create()

@Provides
fun providePostsService(retrofit: Retrofit): ApiService =
    retrofit.create(ApiService::class.java)

@Singleton
@Provides
fun provideApiRemoteDataSource(apiService: ApiService) = ApiRemoteDataSource(apiService)

@Singleton
@Provides
fun provideRepository(
    remoteDataSource: ApiRemoteDataSource
) =
    MainRepo(remoteDataSource)


/**----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------**/

@Singleton
@Provides
fun provideRetrofitEmall(gson: Gson,@ApplicationContext appContext: Context): Retrofit = Retrofit.Builder()
        .client(
                OkHttpClient().newBuilder()
                        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).readTimeout(80,TimeUnit.SECONDS)
                        .addInterceptor(
                                ChuckerInterceptor.Builder(appContext)
                                        .collector(ChuckerCollector(appContext))
                                        .maxContentLength(250000L)
                                        .redactHeaders(emptySet())
                                        .alwaysReadResponseBody(false)
                                        .build()
                        )
                        .build()
        )
        .baseUrl(UtilSingleton.instance!!.GetBaseUrl())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()

@Provides
fun providePostsServiceEmall(retrofit: Retrofit): EmallApiService =
        retrofit.create(EmallApiService::class.java)

@Singleton
@Provides
fun provideApiRemoteDataSource(apiService: EmallApiService) = EmallApiRemoteDataSource(apiService)

@Singleton
@Provides
fun provideRepository(
        remoteDataSource: EmallApiRemoteDataSource
) =
        EmallRepo(remoteDataSource)

}

构建错误->

Execution failed for task ':app:kaptLocalDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)

完整日志 ->

 D:\vaultsNew\vaultspaynewapis\app\build\tmp\kapt3\stubs\localDebug\com\uae\myvaultspay\di\AppModule.java:40: error: Cannot have more than one binding method with the same name in a single module
public final com.uae.myvaultspay.data.remote.ApiRemoteDataSource provideApiRemoteDataSource(@org.jetbrains.annotations.NotNull()
                                                                 ^D:\vaultsNew\vaultspaynewapis\app\build\tmp\kapt3\stubs\localDebug\com\uae\myvaultspay\di\AppModule.java:78: error: Cannot have more than one binding method with the same name in a single module
public final com.uae.myvaultspay.data.remote.emallremote.EmallApiRemoteDataSource provideApiRemoteDataSource(@org.jetbrains.annotations.NotNull()
                                                                                  ^D:\vaultsNew\vaultspaynewapis\app\build\tmp\kapt3\stubs\localDebug\com\uae\myvaultspay\di\AppModule.java:48: error: Cannot have more than one binding method with the same name in a single module
public final com.uae.myvaultspay.data.repository.MainRepo provideRepository(@org.jetbrains.annotations.NotNull()
                                                          ^D:\vaultsNew\vaultspaynewapis\app\build\tmp\kapt3\stubs\localDebug\com\uae\myvaultspay\di\AppModule.java:86: error: Cannot have more than one binding method with the same name in a single module
public final com.uae.myvaultspay.data.repository.EmallRepo provideRepository(@org.jetbrains.annotations.NotNull()
                                                           ^warning: 
File for type 'com.uae.myvaultspay.MyApplication_HiltComponents' created 
in the last round will not be subject to annotation processing.
Execution failed for task ':app:kaptLocalDebugKotlin'.
> A failure occurred while executing 
org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)

【问题讨论】:

    标签: android retrofit2 dagger-hilt


    【解决方案1】:

    如果你想使用 Dagger 或 Hilt 返回 Retrofit 客户端,那么你应该使用@Named 注解。这个注解帮助 Hilt 或 Dagger 用相同的 Retrofit 返回类型来理解你,你需要获取哪个 Retrofit 实例。

    按照以下方式,您可以提供多个带有刀柄或匕首的改造实例。

    首先,我看到您提供了 2 个改造实例。为您提供的每个改造实例添加 @Named 注释。

    object AppModule {
    
       @Singleton
       @Provides
       @Named("Normal")
       fun provideRetrofit(gson: Gson, @ApplicationContext appContext: Context): Retrofit = ...
    
       @Singleton
       @Provides
       @Named("Email")
       fun provideRetrofitEmall(gson: Gson, @ApplicationContext appContext: Context): Retrofit = ...
    }
    

    接下来,当你提供 api 服务时,向 Hilt 或 Dagger 指定它需要哪个改造实例。

    object AppModule {
    
       @Provides
       fun providePostsService(@Named("Normal") retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
    
       @Provides
       fun providePostsServiceEmall(@Named("Email") retrofit: Retrofit): EmallApiService = retrofit.create(EmallApiService::class.java)
    }
    

    最后,清理项目并重新构建项目以查看结果。

    【讨论】:

    • 给定日志后,它实际上不是构建编译时的错误日志。给我看你的完整错误日志。按照此链接,您可以查看完整的错误日志。 stackoverflow.com/a/64830121/15369207
    • 哦,我明白了。您的下一个问题是您有 2 个相同的函数提供名称 provideApiRemoteDataSource()provideRepository()。让我们将它们重命名为不同的函数名并重建。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多