[英]HILT dependency injection
How to inject abstract class I have an abstract class如何注入抽象 class 我有一个抽象 class
abstract class FactoryMediator : xx, yy,zz {}
I am trying to initiate the object for this class using @Module
and @Binds
annotations.我正在尝试使用
@Module
和@Binds
注释为此 class 启动 object。 But that is failed to create and throw an error.但这未能创建并引发错误。
@Module
@InstallIn(SingletonComponent::class)
abstract class PolicyModule {
@Binds
abstract fun bindFactoryMediator(factoryMediator: FactoryMediator): PolicyFactoryMediator
}
But this is giving error.但这给出了错误。 What mistake I did?
我犯了什么错误? Please can you let me know how to create for abstract class.
请让我知道如何为抽象 class 创建。 How can we inject abstract class?
我们如何注入抽象 class? From documentation, it says.
从文档中,它说。 Sometimes a type cannot be constructor-injected.
有时一个类型不能被构造函数注入。 This can happen for multiple reasons.
这可能有多种原因。 For example, you cannot constructor-inject an interface.
例如,您不能构造函数注入接口。 You also cannot constructor-inject a type that you do not own, such as a class from an external library.
您也不能构造函数注入您不拥有的类型,例如来自外部库的 class。 In these cases, you can provide Hilt with binding information by using Hilt modules.
在这些情况下,您可以使用 Hilt 模块为 Hilt 提供绑定信息。
A Hilt module is a class that is annotated with @Module
. Hilt 模块是带有 @Module 注释的
@Module
。 Like a Dagger module, it informs Hilt how to provide instances of certain types.像 Dagger 模块一样,它通知 Hilt 如何提供某些类型的实例。 Unlike Dagger modules, you must annotate Hilt modules with
@InstallIn
to tell Hilt which Android class each module will be used or installed in.与 Dagger 模块不同,您必须使用
@InstallIn
注释 Hilt 模块,以告诉 Hilt 每个模块将被使用或安装在哪个 Android class 中。
You have the method syntax slightly wrong, you currently have:您的方法语法略有错误,您目前有:
@Binds
abstract fun bind(abstractClass: AbstractClass): ImplementationClass
whereas they should be the other way around, so:而它们应该是相反的,所以:
@Binds
abstract fun bind(implementationClass: ImplementationClass): AbstractClass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.