[英]Proper way to inject a class that implements an interface using Hilt
我有
BeatPlayer.kt
interface BeatPlayer {
fun getSession(): MediaSessionCompat
fun playSong(extras: Bundle = bundleOf(BY_UI_KEY to true))
fun playSong(id: Long)
fun playSong(song: Song)
}
class BeatPlayerImplementation(
private val context: Application,
private val musicPlayer: AudioPlayer,
private val songsRepository: SongsRepository,
private val queueUtils: QueueUtils,
private val audioFocusHelper: AudioFocusHelper
) : BeatPlayer {
.........
}
音樂服務.kt
@AndroidEntryPoint
class MusicService : CoroutineService(Main) {
@Inject
lateinit var beatPlayer: BeatPlayer
}
當我運行它說:
[Dagger/MissingBinding] 如果沒有 @Provides 注釋方法,則無法提供 BeatPlayer。
所以我添加了這個:
@Module
@InstallIn(SingletonComponent::class)
abstract class StorageModule {
@Singleton
@Binds
abstract fun bindBeatPlayer(beatPlayer: BeatPlayer): BeatPlayerImplementation
}
現在,我運行,它說:
錯誤:@Binds 方法的參數類型必須可分配給返回類型刀柄
如何正確操作?
我將根據@HenryTest 的評論回答我的問題。
存儲模塊.kt
@Module
@InstallIn(SingletonComponent::class)
abstract class StorageModule {
@Binds
abstract fun bindsPreferenceStorage(preferenceStorageImpl:
PreferenceStorageImpl): PreferenceStorage
@Singleton
@Binds
abstract fun bindBeatPlayer(beatPlayer: BeatPlayerImplementation):
BeatPlayer
}
現在提供 BeatPlayer 實現。
應用模塊.kt
@Singleton
@Provides
fun providesBeatPlayerImplementation(@ApplicationContext context:
Context.,.,.,.) =
BeatPlayerImplementation(
context, .., .., ..,
)
要么
在BeatPlayer 中實現
class BeatPlayerImplementation @Inject constructor(
@ApplicationContext private val context: Application,
.....
) : BeatPlayer {
.........
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.