我想学习干净的建筑,我正在使用 hilt 进行 di。一旦我遇到了 java.lang.RuntimeException:
Unable to instantiate application com.example.cleanarchitecture.MainActivity package com.example.cleanarchitecture: java.lang.ClassCastException: com.example.cleanarchitecture.MainActivity cannot be cast to android.app.Application
错误我已将 SingletonComponent 更改为 ActivityComponent 现在我遇到了我在应用程序的标题中提到的错误。
我的模块就是这样;
@Module
@InstallIn(ActivityComponent::class)
class ProfileDetailModule {
@Singleton
@Provides
fun providesProfileDetailRepository(dataSource: ProfileDataSource): ProfileRepository {
return ProfileRepositoryImpl(dataSource)
}
@Singleton
@Provides
fun providesProfileDataSource(profileApiService: ProfileApiService): ProfileDataSource {
return ProfileDataSource(profileApiService)
}
@Singleton
@Provides
fun providesProfileDetailApiService(retrofit: Retrofit): ProfileApiService =
retrofit.create(ProfileApiService::class.java)
@Module
@InstallIn(ActivityComponent::class)
object AppModule {
@Provides
fun provideApplicationContext(@ActivityContext activity: Activity): Activity {
return activity
}
}
}
我的存储库是;
interface ProfileRepository {
suspend fun getUser(url:String): ProfileResponse
}
这是我的领域类;
class GetUserProfile @Inject constructor(
private val profileRepository: ProfileRepository
): MutableLiveData<ProfileResponse>(){
companion object {
private const val URL =
"https://jsonplaceholder.typicode.com/users/1"
}
data class Params(
val id: Int,
val name: String,
val username: String,
val email: String,
val phone: String,
)
fun execute(
viewModel: ProfileDetailViewModel,
input: Params?
): MutableLiveData<ProfileResponse> {
return MutableLiveData<ProfileResponse>().apply {
input?.let {
viewModel.viewModelScope.launch {
value =
profileRepository.getUser(URL+it.id+it.name+it.username+it.email+it.phone)
}
}
}
}
}
想学习干净的架构所以我脑子里有很多问号。
看了这个问题并不能帮助我; 问题
您可以通过删除文件最后的 AppModule 进行检查吗?对于应用程序,AppModule 必须是单例的,因为它是整个应用程序容器的一个。