Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 630
Ritt Avatar asked Oct 29 '25 14:10

Ritt


1 Answers

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

like image 198
Bartek Lipinski Avatar answered Nov 01 '25 03:11

Bartek Lipinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!