注入 Hilt 未实例化的任意逻辑 class

Inject into arbitrary Logic class that is not instanciated by Hilt

我目前正在将一个应用程序从 anko-sqlite 迁移到 room,因为 anko 已经停产很久了。在这样做的过程中,我引入了一个存储库层,并认为我会尝试引入依赖注入以获取对我所有 classes 中的存储库实例的引用。

在此之前,我使用了一个单例实例,我刚刚将其推入我的应用程序 classes 伴生对象并从任何地方访问它。

我设法将我的存储库注入 Fragments、Workmanager 和 Viewmodels。但我现在确实有点难以理解他们是如何预见到我们应该用任意逻辑来处理这个问题的 classes.

例如,我的 workmanager worker 调用一个 class 来实例化一个“工作”列表,这些工作需要访问存储库。工人本身实际上什至需要访问存储库,因为所有工作都从它那里抽象出来。

我怎样才能做出这样的作品

class Job(val someExtraArgINeed: Int) {

@Inject
lateinit var someRepository: SomeRepository   // <= this should be injected when the job is instanciated with the constructor that already exists

}

对于 Activity 等,我们有特殊的注释 @AndroidEntryPoint 来实现这一点。但是,文档不清楚我们应该如何从任何其他 class 获取我们的实例,而不是 Android class。我知道构造函数注入是推荐使用的东西。但我认为如果没有比现在更大的折射镜,它在这里对我不起作用。

如果我正确理解你的问题,你可以像这样使用hilt entry points

class CustomClass(applicationContext: Context) {

    @EntryPoint
    @InstallIn([/*hilt component that provide SomeRepository*/ApplicationComponent]::class)
    interface SomeRepositoryEntryPoint {
        fun provideSomeRepository(): SomeRepository
    }

    private val someRepository by lazy {
        EntryPointAccessors.fromApplication(applicationContext, SomeRepositoryEntryPoint::class.java).provideSomeRepository()
    }

    fun doSomething() {
        someRepository.doSomething()
    }

}