[英]Hilt - How can I inject dependencies into adapter?
我在模块中提供依赖:
@Provides
@Singleton
fun provideImageUtil(@ImageUrl imageUrl: String): ImageUtil = GlideImageUtil(imageUrl)
我正在尝试将其注入 RecyclerView 适配器:
class MainAdapter(private val goods: ArrayList<GoodItem>) : RecyclerView.Adapter<MainAdapter.DataViewHolder>() {
@Inject
lateinit private var imageUtil: ImageUtil
我曾经使用 Dagger 以这种方式注入:
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 将依赖项注入适配器? 据我所知,“appComponent”是由 Hilt 生成的。 我怎样才能访问它?
首先在您的自定义 class 中创建入口点
@EntryPoint
@InstallIn(SingletonComponent::class)
interface MyEntryPoint {
fun getImageUtil(): ImageUtil
}
它是带有@EntryPoint
注释的简单接口。 由于您的依赖项(ImageUtil)是 singleton,您应该使用@InstallIn(SingletonComponent::class)
注释来声明组件。 最后声明一个方法来获取你的依赖fun getImageUtil(): ImageUtil
您可以在适配器的 init 块中获取依赖项
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
您必须添加一个@AndroidEntryPoint
并且可能必须注入构造函数,
因为imageUrl
需要来自某个地方; 例如来自 Gradle:
javaCompileOptions {
annotationProcessorOptions {
arguments += ["imageUrl": "..."]
}
}
而且我认为@Singleton @Provides
/ @Singleton @Binds
注释确实需要 scope。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.