Hilt注入MyInterface实现列表遇编译错误,求解决方法
问题描述
接口定义
interface MyInterface { }
两个实现类
@Singleton class Implementation1 @Inject constructor( private val gson: Gson, ) : MyInterface { }
@Singleton class Implementation2 @Inject constructor( @ApplicationContext private val context: Context, ) : MyInterface { }
仓库类需求
需要一个包含所有MyInterface实现类实例的仓库:
@Singleton class MyRepository @Inject constructor( private val implementations: List<MyInterface>, ) { }
尝试的DI配置(报错)
@InstallIn(SingletonComponent::class) @Module object MyDiModule { @Provides fun providesImplementations( imp1: Implementation1, imp2: Implementation2, ): List<MyInterface> { return listOf(imp1, imp2) } }
编译错误信息
/home/sayantan/AndroidStudioProjects/example/app/build/generated/hilt/component_sources/debug/com/example/ExampleApplication_HiltComponents.java:188: error: [Dagger/MissingBinding] java.util.List<? extends com.example.MyInterface> cannot be provided without an @Provides-annotated method. public abstract static class SingletonC implements FragmentGetContextFix.FragmentGetContextFixEntryPoint, ^
解决方案
这个错误的核心原因是Dagger/Hilt在解析List<MyInterface>依赖时,默认会尝试匹配List<? extends MyInterface>类型的绑定,而你提供的List<MyInterface>与该类型不兼容。以下两种方法可以解决问题:
方法一:修正@Provides方法的返回类型
将providesImplementations的返回类型改为协变的List<out MyInterface>,与Dagger期望的类型对齐:
@InstallIn(SingletonComponent::class) @Module object MyDiModule { @Provides fun providesImplementations( imp1: Implementation1, imp2: Implementation2, ): List<out MyInterface> { return listOf(imp1, imp2) } }
方法二:用@IntoCollection自动收集实现类
无需手动构建List,通过@IntoCollection注解让Hilt自动收集所有MyInterface的实现类实例:
创建一个抽象模块类,用@Binds结合@IntoCollection绑定每个实现类:
@InstallIn(SingletonComponent::class) @Module abstract class MyInterfaceModule { @Binds @IntoCollection abstract fun bindImplementation1(impl1: Implementation1): MyInterface @Binds @IntoCollection abstract fun bindImplementation2(impl2: Implementation2): MyInterface }
之后Hilt会自动把所有标记了@IntoCollection的MyInterface实现实例收集到List中,直接注入到MyRepository的构造参数里。这种方式更符合DI框架的设计思路,后续新增实现类时只需添加对应的绑定方法即可,无需修改List构建逻辑。
内容的提问来源于stack exchange,提问作者SayantanRC
相关产品推荐
相关产品推荐

