简体   繁体   English

如何使用 Dagger2 为 Android 提供 Room Dao 依赖项?

[英]How to provide Room Dao dependency using Dagger2 for Android?

My repository passes in a Room Persistence lib.我的存储库传入一个 Room Persistence 库。 Dao object as a dependency.道 object 作为依赖。 The problem is Dao is an interface.问题是 Dao 是一个接口。 The most recent suggestion by Google is to do the following: Google 的最新建议是执行以下操作:

// Tells Dagger this is a Dagger module
// Because of @Binds, StorageModule needs to be an abstract class
@Module
abstract class StorageModule {

    // Makes Dagger provide SharedPreferencesStorage when a Storage type is requested
    @Binds
    abstract fun provideStorage(storage: SharedPreferencesStorage): Storage
}

In the example above, SharedPreferencesStorage is a user created implementation of the interface, Storage .在上面的示例中, SharedPreferencesStorage是用户创建的接口Storage的实现。 The problem with Room dao dependencies is that the implementation is generated by the library like roomDatabase.getDatabase(context).myDao() . Room dao 依赖项的问题在于实现是由诸如roomDatabase.getDatabase(context).myDao()之类的库生成的。 The most recent Dagger version seems to avoid using the old way of passing in component dependencies through a module constructor.最新的 Dagger 版本似乎避免使用通过模块构造函数传递组件依赖项的旧方式。 Is there a way to do this using @Subcomponent.Factory or @Component.Factory , or is the "old" way the only way to do this for Room dao dependencies?有没有办法使用@Subcomponent.Factory@Component.Factory来做到这一点,或者“旧”方式是对 Room dao 依赖项执行此操作的唯一方法?

You could try the following approach:您可以尝试以下方法:

@Module
class DatabaseModule {
    @Provides
    fun provideDaoA(db: MyDb): DaoA = db.daoA()

    @Provides
    fun provideDaoB(db: MyDb): DaoB = db.daoB()
}

class MyRepository @Inject constructor(private val daoA: DaoA) {..}

Another approach from googlesamples : googlesamples 的另一种方法:

    @JvmStatic
    @Singleton
    @TasksLocalDataSource
    @Provides
    fun provideTasksLocalDataSource(
        database: ToDoDatabase,
        ioDispatcher: CoroutineDispatcher
    ): TasksDataSource {
        return TasksLocalDataSource(
            database.taskDao(), ioDispatcher
        )
    }

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

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