我在模块中提供依赖:
@Provides
@Singleton
fun provideImageUtil(@ImageUrl imageUrl: String): ImageUtil = GlideImageUtil(imageUrl)
我正在尝试将其注入(inject) RecyclerView 适配器:class MainAdapter(private val goods: ArrayList<GoodItem>) : RecyclerView.Adapter<MainAdapter.DataViewHolder>() {
@Inject
lateinit private var imageUtil: ImageUtil
我曾经使用 Dagger 以这种方式注入(inject):object Injector {
lateinit var appComponent: AppComponent
fun initAppComponent(context: Context){
if(context is Activity){
throw IllegalStateException("pass an Application as an argument to avoid memory leaks")
}
appComponent = DaggerAppComponent.builder()
.appModule(AppModule(context))
.build()
}
}
在适配器中:init {
Injector.appComponent.inject(this)
}
如何使用 Hilt 将依赖项注入(inject)适配器?据我所知,“appComponent”是由 Hilt 生成的。我怎样才能访问它?
最佳答案
首先在您的自定义类中创建入口点
@EntryPoint
@InstallIn(SingletonComponent::class)
interface MyEntryPoint {
fun getImageUtil(): ImageUtil
}
它是与@EntryPoint
的简单界面注解。由于您的依赖项 (ImageUtil) 是单例的,您应该使用 @InstallIn(SingletonComponent::class)
声明组件的注释。最后声明一个方法来获取你的依赖fun getImageUtil(): ImageUtil
您可以在适配器的 init block 中获取依赖项init {
val myEntryPoint = EntryPointAccessors.fromApplication(context, MyEntryPoint::class.java)
imageUtil = myEntryPoint.getImageUtil()
}
完整代码class MainAdapter(
context: Context,
private val goods: ArrayList<GoodItem>
) : RecyclerView.Adapter<MainAdapter.DataViewHolder>() {
var imageUtil: ImageUtil
@EntryPoint
@InstallIn(SingletonComponent::class)
interface MyEntryPoint {
fun getImageUtil(): ImageUtil
}
init {
val myEntryPoint = EntryPointAccessors.fromApplication(context, MyEntryPoint::class.java)
imageUtil = myEntryPoint.getImageUtil()
}
}
另见 https://developer.android.com/training/dependency-injection/hilt-android#not-supported
关于android - Hilt - 如何将依赖项注入(inject)适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67394870/