在 Fragment 和 Activity 之外通过 Hilt 进行场注入

hal*_*rkk 4 android dependency-injection kotlin dagger-hilt

我想知道是否可以在片段或活动之外使用场注入?我知道我可以使用构造函数注入,但我想知道是否也可以使用字段注入。我认为 Dagger 是可能的。

当我尝试对注入的yclass字段执行某些操作时出现此错误

lateinit property yClass has not been initialized
Run Code Online (Sandbox Code Playgroud)

但它是在我创建的模块中初始化的。

根据文档,我需要使用 @AndroidEntryPoint 注释来使用字段注入,但在这种情况下,我收到此错误:

@AndroidEntryPoint base class must extend ComponentActivity, (support) Fragment, View, Service, or BroadcastReceiver.
Run Code Online (Sandbox Code Playgroud)

注意:它在活动中没有错误

基本上,我想做这样的事情,

class XClass() {

@Inject
lateinit var yClass: YClass

}
Run Code Online (Sandbox Code Playgroud)

提前致谢,

小智 5

要对自定义类使用字段注入,您需要使用@EntryPoint 注解。想要查询更多的信息:

https://developer.android.com/training/dependency-injection/hilt-android#not-supported

或代码实验室:

https://developer.android.com/codelabs/android-hilt#10

  • 据我了解,我仍然需要 appContext 才能在定义入口点时获得依赖项,有没有办法不用它? (2认同)