繁体   English   中英

无法使用 Hilt、Android 注入 Room dao

[英]Can't inject Room dao using Hilt, Android

我正在尝试使用 Hilt 将 Room DAO 注入到存储库中。 我正在使用以下代码:

def room_version = "2.2.6"
ext.hilt_version = '2.33-beta'

implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
implementation "androidx.room:room-guava:$room_version"
testImplementation "androidx.room:room-testing:$room_version"

implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-compiler:$hilt_version"

@Dao
interface SearchDAO {

    @Query("SELECT * FROM searches_table WHERE name LIKE '%' || :query || '%'")
    fun readSearches(query : String) : Flow<List<SearchItem>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSearch(search : SearchItem)

    @Delete
    suspend fun deleteSearch(search: SearchItem)
}

数据库

@Database(
        entities = [SearchItem::class],
        version = 1
)
abstract class SearchesDatabase : RoomDatabase(){
    abstract fun getSearchesDao() : SearchDAO
}

提供者

@Module
@InstallIn(ActivityComponent::class)
object AppModule{
    @Singleton
    @Provides
    fun provideSearchDatabase(@ApplicationContext context : Context) =
        Room.databaseBuilder(context, SearchesDatabase::class.java, SEARCH_DATABASE_NAME)
            .fallbackToDestructiveMigration()
            .build()

    @Provides
    fun provideSearchDAO(appDatabase: SearchesDatabase): SearchDAO {
        return appDatabase.getSearchesDao()
    }
}

基础应用

@HiltAndroidApp
class BaseApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        //Timber.plant(Timber.DebugTree())
    }
}

存储库注入

class Repository @Inject constructor(
    val searchesDao : SearchDAO
){
...
}

问题是我收到以下错误:

[Dagger/MissingBinding] com.example.leagueapp.database.SearchDAO 不能在没有@Provides-annotated 方法的情况下提供。 公共抽象 static class SingletonC 实现 BaseApplication_GeneratedInjector

简短的回答:任何@Singleton 都必须安装在 SingletonComponent 中。

说明:单身人士的目的是为了他们所处的过程的生命。您的数据库是 singleton(可能应该是)但是您正在使用@InstallIn(ActivityComponent::class)告诉 dagger provide的所有内容本模块中的范围应限于活动的生命周期; 当活动死亡时,模块死亡。

请在您的应用模块 class 中编写以下代码。 你只需要在 @installIn() 注释中写 SingletonComponent::class 而不是 ActivityComponent::class :)

@Module
@InstallIn(SingletonComponent::class)
object AppModule{
    @Singleton
    @Provides
    fun provideSearchDatabase(@ApplicationContext context : Context) =
        Room.databaseBuilder(context, SearchesDatabase::class.java, SEARCH_DATABASE_NAME)
            .fallbackToDestructiveMigration()
            .build()

    @Provides
    fun provideSearchDAO(appDatabase: SearchesDatabase): SearchDAO {
        return appDatabase.getSearchesDao()
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM