【发布时间】:2021-08-25 14:02:39
【问题描述】:
有人在 Realm 数据库中使用过 Dagger Hilt。我遇到初始化问题。也许上面的解决方案会起作用。
错误->
需要由 Hilt 实例化的模块必须有一个可见的空构造函数。 [Hilt] 处理未完成。有关详细信息,请参阅上面的错误。 任务 ':app:kaptDebugKotlin' 执行失败。 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障 java.lang.reflect.InvocationTargetException(没有错误信息)`
我的模块->
@Module
@InstallIn(SingletonComponent::class)
class LocalDataSourceModule(context: Context) {
init {
Realm.init(context)
}
@Provides
fun provideLocalDataSource(realm: Realm): LocalDataSource = LocalDataSourceImpl(realm)
@Singleton
@Provides
fun provideRealm(configuration: RealmConfiguration): Realm =
try {
Realm.getDefaultInstance()
} catch (e: Exception) {
Realm.getInstance(configuration)
}
@Singleton
@Provides
fun provideRealmConfiguration(): RealmConfiguration = RealmConfiguration.Builder().build()
}
我的应用程序->
@HiltAndroidApp
class BaseApplication : Application() {
lateinit var girlComponent: GirlComponent
private set
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
girlComponent = DaggerGirlComponent.builder().localDataSourceModule(
LocalDataSourceModule(applicationContext)
).build()
}
}
【问题讨论】:
-
从未使用过 Hilt,但错误是说您的模块没有无参数构造函数,它没有。在模块中删除构造函数参数,并在其他地方或
provideRealm函数中通过传递Context作为参数并返回Realm,就像您创建的任何其他依赖项一样。 -
然后我得到它错误:@Provides 方法必须返回一个值(非 void) public final void provideRealmContext(@org.jetbrains.annotations.NotNull()
标签: android kotlin dependency-injection realm dagger-hilt