无法使用 Hilt 注入 Room dao,Android

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

@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 cannot be provided without an @Provides-annotated method. public abstract static class SingletonC implements BaseApplication_GeneratedInjector

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

解释:单例的意思是在它们所处的进程的生命周期内存在。您的数据库是单例(它可能应该是)但您使用的是 @InstallIn(ActivityComponent::class),它告诉 dagger 一切是本模块中的 provided 应限定在 activity 的生命周期内;当 Activity 死亡时,模块死亡。

请在您的应用程序模块中编写以下代码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()
    }
}