我正在使用Hilt进行DI,我有这个课程。
class ChatCore @Inject constructor()
此类需要插入片段中,而不必将片段标记为@AdroidEntryPoint
,因为该片段可以附加到未标记为@AndroidEntryPoint
的活动中。
我该如何做到这一点。我尝试使用EntryPoint,但最终出现错误。
class MyFragment : Fragment() {
lateinit var chatCore: ChatCore
@EntryPoint
@InstallIn(FragmentComponent::class)
interface ChatCoreProviderEntryPoint{
fun chatCore():ChatCore
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val hiltEntryPoint = EntryPointAccessors.fromFragment(this, ChatCoreProviderEntryPoint::class.java)
chatCore = hiltEntryPoint.chatCore()
}
通过将其添加到应用程序容器中来解决。
@EntryPoint
@InstallIn(ApplicationComponent::class)
interface ChatCoreProviderEntryPoint{
fun chatCore():ChatCore
}
val hiltEntryPoint = EntryPointAccessors.fromApplication(applicationContext,
ChatCoreProviderEntryPoint::class.java)
答案 0 :(得分:0)
如果您不想为AndroidEntryPoint
使用Fragment
,则需要@Install
在另一个Component
中的模块(包含依赖项)。
例如。在ApplicationComponent
而非FragmentComponent
中。
然后,您还需要使用相应的EntryPointAccessors.fromXyz(...)
方法。例如。对于安装在ApplicationComponent
中的模块,您应该使用EntryPointAccessors.fromApplication(...)
。