Search code examples
androidkotlindagger-hilt

Hilt - EntryPoint in Fragment


I am using Hilt for DI and I have this class.

class ChatCore @Inject constructor()

This class needs to be injected in fragment , without marking the fragment as @AdroidEntryPoint as this fragment can be attached to activity which isn't marked as @AndroidEntryPoint

How can i achieve this. I tried using EntryPoint but i end up with error.

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()
  }

Solved it by adding it into the application container.

      @EntryPoint
      @InstallIn(ApplicationComponent::class)
      interface ChatCoreProviderEntryPoint{
        fun chatCore():ChatCore
      }


      val hiltEntryPoint = EntryPointAccessors.fromApplication(applicationContext,
         ChatCoreProviderEntryPoint::class.java)

Solution

  • If you don't want to use AndroidEntryPoint for your Fragment you need to @Install your module (containing your dependency) within a different Component. E.g. within the ApplicationComponent not the FragmentComponent.

    Then you will also need to use the corresponding EntryPointAccessors.fromXyz(...) method. E.g. for a module installed in the ApplicationComponent you should be using EntryPointAccessors.fromApplication(...).