通过 Fragment 和 Activity 外部的 Hilt 进行字段注入

Field Injection via Hilt outside of Fragment and Activity

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

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

lateinit property yClass has not been initialized

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

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

@AndroidEntryPoint base class must extend ComponentActivity, (support) Fragment, View, Service, or BroadcastReceiver.

Note: It is working without an error at the activity

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

class XClass() {

@Inject
lateinit var yClass: YClass

}

提前致谢,

要为自定义 类 使用字段注入,您需要使用 @EntryPoint 注释。更多信息:

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

或代码实验室:

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