![](/img/trans.png)
[英]Android Hilt dagger inject interface in viewModel @ViewModelInject got UninitializedPropertyAccessException
[英]Android + Hilt: Cannot inject interface
我有一个 class 扩展接口如下:
class AWSTestTypeService : IAWSTestTypeService {
override fun getTestTypes(): List<TestTypeDTO>?
{
val pAWS = instance
return pAWS!!.getTestTypes()
}
}
以及对应的界面:
interface IAWSTestTypeService {
fun getTestTypes(): List<TestTypeDTO>?
}
并尝试通过下一个模块注入它:
@Module
@InstallIn(SingletonComponent::class)
abstract class Dependencies {
@EntryPoint
@InstallIn(SingletonComponent::class)
interface IEntryPoint{
fun awsTestTypeService(): IAWSTestTypeService
}
@Binds
@Singleton
abstract fun bindsAWSTestTypeService(
awsTestTypeService: AWSTestTypeService
): IAWSTestTypeService
}
并要求它:
class FreddieMercuryClass {
private lateinit var awsTestTypeService : IAWSTestTypeService
init {
setDependencies()
}
private fun setDependencies(){
val entryPointServices = EntryPointAccessors.fromApplication(tm.context, DependenciesServices.IEntryPoint::class.java)
this.awsTestTypeService = entryPointServices.awsTestTypeService()
}
}
但是在编译时出现以下 Hilt 错误:
/Users/xxx/StudioProjects/app_name/app/build/generated/hilt/component_sources/debug/com/xxx/xxx/ui/app/TMApplication_HiltComponents.java:161: error: [Dagger/MissingBinding] xxx.xxx.xxx.services.aws.AWSTestSubjectService cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract static class SingletonC implements xxx.xxx.xxx.common.dependencies.Dependencies.IEntryPoint,
^
xxx.xxx.xxx.services.aws.AWSTestSubjectService is injected at
xxx.xxx.xxx.dependencies.Dependencies.bindAWSTestSubjectService(awsTestSubjectService)
xxx.xxx.xxx.core.iservice.aws.IAWSTestSubjectService is requested at
xxx.xxx.xxx.dependencies.Dependencies.IEntryPoint.awsTestSubjectService()
怎么了?
在您的 CryptoCurrencyViewModelFactory 构造函数中,将私有 val 创建者:Map<Class 更改为私有 val 创建者:MutableMap<Class。 Kotlin 的 Map 强制不变,但在内部 Dagger 需要 map 是可变的。
检查您的源代码后,我注意到您在 CryptoCurrencyViewModelFactory ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 将其更改为正确的导入 (javax.inject.Inject),否则 Dagger 将无法识别 @Inject 注释。
经过长时间的调查发现,如果您没有在要注入的类中指定/注入一个空的构造函数(以及它们相应的接口也将被注入),那么 Hilt 不知道如何提供它们,因此出现错误:
如果没有 @Inject 构造函数或 @Provides-annotated 方法,则无法提供。
因此,解决方案就像 @Inject(ing) 在要注入的类中的一个空构造函数一样简单(当然,还没有一个)。
class FreddieMercuryClass
@Inject constructor() {
private lateinit var awsTestTypeService : IAWSTestTypeService
init {
setDependencies()
}
private fun setDependencies(){
val entryPointServices = EntryPointAccessors.fromApplication(tm.context, DependenciesServices.IEntryPoint::class.java)
this.awsTestTypeService = entryPointServices.awsTestTypeService()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.