简体   繁体   English

使用 Hilt 注入实现接口的类的正确方法

[英]Proper way to inject a class that implements an interface using Hilt

I have我有

BeatPlayer.kt 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 {
 .........

 }

MusicService.kt音乐服务.kt

@AndroidEntryPoint
class MusicService :  CoroutineService(Main) {
   @Inject
  lateinit var beatPlayer: BeatPlayer
}

When I run it says:当我运行它说:

[Dagger/MissingBinding] BeatPlayer cannot be provided without an @Provides-annotated method. [Dagger/MissingBinding] 如果没有 @Provides 注释方法,则无法提供 BeatPlayer。

So I added this:所以我添加了这个:

@Module
@InstallIn(SingletonComponent::class)
abstract class StorageModule {
@Singleton
@Binds
abstract fun bindBeatPlayer(beatPlayer: BeatPlayer): BeatPlayerImplementation
}

Now, I run, it says:现在,我运行,它说:

error: @Binds methods' parameter type must be assignable to the return type hilt错误:@Binds 方法的参数类型必须可分配给返回类型刀柄

How to do it properly?如何正确操作?

I will answer my question based on comment from @HenryTest.我将根据@HenryTest 的评论回答我的问题。

StorageModule.kt存储模块.kt

@Module
@InstallIn(SingletonComponent::class)
abstract class StorageModule {
@Binds
abstract fun bindsPreferenceStorage(preferenceStorageImpl: 
PreferenceStorageImpl): PreferenceStorage

@Singleton
@Binds
abstract fun bindBeatPlayer(beatPlayer: BeatPlayerImplementation): 
BeatPlayer
}

Now Provide BeatPlayerImplementation.现在提供 BeatPlayer 实现。

AppModule.kt应用模块.kt

 @Singleton
 @Provides
 fun providesBeatPlayerImplementation(@ApplicationContext context: 
 Context.,.,.,.) = 
 BeatPlayerImplementation(
    context, .., .., ..,  
 )

OR要么

In BeatPlayerImplementationBeatPlayer 中实现

 class BeatPlayerImplementation @Inject constructor(
 @ApplicationContext private val context: Application,
 .....
 ) : BeatPlayer {
 .........
 }

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

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