[英]Inject into arbitrary Logic class that is not instanciated by Hilt
我目前正在將應用程序從anko-sqlite
遷移到room
因為 anko 很久以前就已經停產了。 在這樣做的過程中,我引入了一個存儲庫層,並認為我會嘗試引入依賴注入來獲取對我所有類中的存儲庫實例的引用。
在此之前,我使用了一個單例實例,我只是將它塞入我的應用程序類伴隨對象並從任何地方訪問它。
我設法將我的存儲庫注入 Fragments、Workmanager 和 Viewmodels。 但是我現在確實有點難以理解他們認為我們應該如何使用任意邏輯類來處理這個問題。
例如,我的 workmanager 工作人員調用了一個類,該類實例化了“作業”列表,並且那些需要訪問存儲庫的人員。 工作人員本身實際上甚至確實需要訪問存儲庫,因為所有工作都從中抽象出來。
我怎樣才能做這樣的工作
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
}
對於活動等,我們有特殊的注釋@AndroidEntryPoint
使這項工作有效。 但是,文檔並不清楚我們應該如何從不是 Android 類的任何其他類中獲取我們的實例。 我知道構造函數注入是推薦使用的東西。 但是我認為如果沒有比現在更大的折射器,它不會對我有用。
如果我正確理解您的問題,您可以使用這樣的hilt 入口點
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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.