Hilt - 将依赖项从应用程序注入到模块
Hilt - inject dependency from app to module
假设我有 Android 个应用程序项目,其中包含一个主“应用程序”模块和一个“模块 1”模块。 “app”依赖于“module1”
implementation project(":module1")
我开始使用 Hilt 将依赖项从“app”注入到“module1”。
在“module1”中我定义了接口
interface TestInterface {
fun doSomething()
}
我在“app”中实现的
class Test: TestInterface {
override fun doSomething() {
Log.i("Test", "Something")
}
}
现在,我想将“Test”实现注入“module1”并使用它。
我创建了测试 class:
class Work {
@Inject
lateinit var test: TestInterface
fun doWork() {
test.doSomething()
}
}
我尝试在 MainActivty 中使用它
Work().doWork()
但是不行。
kotlin.UninitializedPropertyAccessException: lateinit property test has not been initialized
at module1.Work.getTest(Work.kt:8)
at module1.Work.doWork(Work.kt:11)
我设置了:
@AndroidEntryPoint
class MainActivity
和
@HiltAndroidApp
class HiltApplication
刀柄模块:
@Module
@InstallIn(SingletonComponent::class)
interface Dependencies {
@Binds
fun bindsTestInterface(test: Test): TestInterface
}
知道为什么这不起作用吗?
这是解决方案,以备不时之需。
主要活动
@Inject
lateinit var work: Work
刀柄模块
@Module
@InstallIn(SingletonComponent::class)
object Dependencies {
@Provides
@Singleton
fun bindsTestInterface(): TestInterface {
return Test()
}
}
工作
class Work @Inject constructor() {
@Inject
lateinit var test: TestInterface
fun doWork() {
test.doSomething()
}
}
假设我有 Android 个应用程序项目,其中包含一个主“应用程序”模块和一个“模块 1”模块。 “app”依赖于“module1”
implementation project(":module1")
我开始使用 Hilt 将依赖项从“app”注入到“module1”。
在“module1”中我定义了接口
interface TestInterface {
fun doSomething()
}
我在“app”中实现的
class Test: TestInterface {
override fun doSomething() {
Log.i("Test", "Something")
}
}
现在,我想将“Test”实现注入“module1”并使用它。 我创建了测试 class:
class Work {
@Inject
lateinit var test: TestInterface
fun doWork() {
test.doSomething()
}
}
我尝试在 MainActivty 中使用它
Work().doWork()
但是不行。
kotlin.UninitializedPropertyAccessException: lateinit property test has not been initialized
at module1.Work.getTest(Work.kt:8)
at module1.Work.doWork(Work.kt:11)
我设置了:
@AndroidEntryPoint
class MainActivity
和
@HiltAndroidApp
class HiltApplication
刀柄模块:
@Module
@InstallIn(SingletonComponent::class)
interface Dependencies {
@Binds
fun bindsTestInterface(test: Test): TestInterface
}
知道为什么这不起作用吗?
这是解决方案,以备不时之需。
主要活动
@Inject
lateinit var work: Work
刀柄模块
@Module
@InstallIn(SingletonComponent::class)
object Dependencies {
@Provides
@Singleton
fun bindsTestInterface(): TestInterface {
return Test()
}
}
工作
class Work @Inject constructor() {
@Inject
lateinit var test: TestInterface
fun doWork() {
test.doSomething()
}
}