簡體   English   中英

Android + 刀柄:無法注入接口

[英]Android + Hilt: Cannot inject interface

我有一個 class 擴展接口如下:

class AWSTestTypeService : IAWSTestTypeService {

    override fun getTestTypes(): List<TestTypeDTO>?
    {
        val pAWS = instance
        return pAWS!!.getTestTypes()
    }
}

以及對應的界面:

interface IAWSTestTypeService {
    fun getTestTypes(): List<TestTypeDTO>?
}

並嘗試通過下一個模塊注入它:

@Module
@InstallIn(SingletonComponent::class)
abstract class Dependencies {

    @EntryPoint
    @InstallIn(SingletonComponent::class)
    interface IEntryPoint{
        fun awsTestTypeService(): IAWSTestTypeService
    }

    @Binds
    @Singleton
    abstract fun bindsAWSTestTypeService(
        awsTestTypeService: AWSTestTypeService
    ): IAWSTestTypeService
}

並要求它:

class FreddieMercuryClass {

    private lateinit var awsTestTypeService : IAWSTestTypeService

    init {
        setDependencies()
    }

    private fun setDependencies(){
        val entryPointServices = EntryPointAccessors.fromApplication(tm.context, DependenciesServices.IEntryPoint::class.java)
        this.awsTestTypeService = entryPointServices.awsTestTypeService()
    }
}

但是在編譯時出現以下 Hilt 錯誤:

/Users/xxx/StudioProjects/app_name/app/build/generated/hilt/component_sources/debug/com/xxx/xxx/ui/app/TMApplication_HiltComponents.java:161: error: [Dagger/MissingBinding] xxx.xxx.xxx.services.aws.AWSTestSubjectService cannot be provided without an @Inject constructor or an @Provides-annotated method.
  public abstract static class SingletonC implements xxx.xxx.xxx.common.dependencies.Dependencies.IEntryPoint,
                         ^
      xxx.xxx.xxx.services.aws.AWSTestSubjectService is injected at
          xxx.xxx.xxx.dependencies.Dependencies.bindAWSTestSubjectService(awsTestSubjectService)
      xxx.xxx.xxx.core.iservice.aws.IAWSTestSubjectService is requested at
          xxx.xxx.xxx.dependencies.Dependencies.IEntryPoint.awsTestSubjectService()

怎么了?

在您的 CryptoCurrencyViewModelFactory 構造函數中,將私有 val 創建者:Map<Class 更改為私有 val 創建者:MutableMap<Class。 Kotlin 的 Map 強制不變,但在內部 Dagger 需要 map 是可變的。

檢查您的源代碼后,我注意到您在 CryptoCurrencyViewModelFactory ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 將其更改為正確的導入 (javax.inject.Inject),否則 Dagger 將無法識別 @Inject 注釋。

經過長時間的調查發現,如果您沒有在要注入的類中指定/注入一個空的構造函數(以及它們相應的接口也將被注入),那么 Hilt 不知道如何提供它們,因此出現錯誤:

如果沒有 @Inject 構造函數或 @Provides-annotated 方法,則無法提供。

因此,解決方案就像 @Inject(ing) 在要注入的類中的一個空構造函數一樣簡單(當然,還沒有一個)。

class FreddieMercuryClass 
@Inject constructor() {

    private lateinit var awsTestTypeService : IAWSTestTypeService

    init {
        setDependencies()
    }

    private fun setDependencies(){
        val entryPointServices = EntryPointAccessors.fromApplication(tm.context, DependenciesServices.IEntryPoint::class.java)
        this.awsTestTypeService = entryPointServices.awsTestTypeService()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM