【发布时间】:2021-05-08 05:04:53
【问题描述】:
我想在Service 中注入一个类。让我们看看下面的代码:
class DeviceUtil @Inject constructor() {
...
}
@AndroidEntryPoint
class LocationUpdateService : Service() {
@Inject
lateinit var deviceUtil: DeviceUtil
...
}
@Inject lateinit var deviceUtil: DeviceUtil 在 Activity 中工作正常,但在 Service 中不工作。
它给出了错误: kotlin.UninitializedPropertyAccessException: lateinit property deviceUtil has not been initialized
【问题讨论】:
-
所以,我错误地忘记在 onCreate 方法中调用
super.onCreate(),通过添加这个解决了我的问题。 -
在我的情况下,它仍然不能通过添加 super.onCreate() 来解决,现在它告诉我如果没有 @Provides-annotated 方法就无法提供我注入的 useCase(我将它绑定在我的用例模块),尽管它在我的视图模型上运行良好(通过构造函数注入)
-
我没有得到你的问题,你能分享一下你的实施快照吗?但是,我认为您需要为特定的用例类使用 @Provides 或使用构造函数注入。
-
原来我将用例模块的范围限定为activityRetainedComponent,同时将该用例注入服务(用AndroidentryyPoint注释),对我来说,我只是将用例模块和存储库模块的范围更改为ApplicationComponent,这行得通对我来说很好
标签: android dependency-injection dagger-2 dagger-hilt