Search code examples
androidandroid-roomdagger-2

Dagger, how to create DAO module


I need some help on how to implement Dagger in an app using ROOM, I'm stuck on creating a module for the DAO interface.

daoModule

@Module
abstract class daoModule {
    @Binds
    abstract fun provideDao(dao: WordDao): WordDao
}

Error

 public abstract com.example.daggerroom.Room.WordDao provideDao(@org.jetbrains.annotations.NotNull()
                                                        ^C:\Android\DaggerRoom\app\build\tmp\kapt3\stubs\debug\com\example\daggerroom\di\AppComponent.java:6: error:

I would appreciate any comments on this as I've been stuck on this for over a week and I'm just not sure how to implement Dagger with Room.


Solution

  • First you need to be able to provide an instance of Database and then you can get your Dao from the Db:

    @Module
    abstract class DaoModule {
        companion object {
            
            @Provides
            @Singleton
            fun provideDatabase(application: Application): YourDb {
                return Room.databaseBuilder(application, YourDb.class, "db").build()
            }
    
            @Provides
            @Singleton
            fun provideWordDao(database: YourDb): WordDao {
                return database.getWordDao()
            }
        }
    
        // Binds methods...
    }