简体   繁体   中英

How to get component dependencies in Dagger 2 module using Kotlin on Android?

I have a Dagger2 Component for Fragment on Android. I initialize the component by injecting the fragments dynamically. Now, I need to provide activity context to dependencies from the fragment module. I assumed writing a provider method with Fragment as a parameter will automatically get me the Fragment reference in the module, and I can extract the context out of it. But I can't compile my code.

The application component also offers a Context, therefore I have added a qualifier to get activity context. That shouldn't create any issues I believe. Here's my code :

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class FragmentScope

@FragmentScope
@Component(modules = [FragmentModule::class],
        dependencies = [AppComponent::class])

interface FragmentComponent {
    fun inject(myFragment: MyFragment)

    @Component.Builder
    interface Builder {
        fun appComponent(component: AppComponent): Builder
        fun build(): FragmentComponent
    }
}

@Module
object FragmentModule {
    @Provides
    @JvmStatic
    @Named("Fragment")
    fun provideContext(myFragment: MyFragment): Context = myFragment.context!!
}

Compilation Error:

[Dagger/MissingBinding] MyFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
    public abstract void inject(@org.jetbrains.annotations.NotNull()
                         ^
  A binding with matching key exists in component: FragmentComponent

I think you are mistaking the inject method of the FragmentComponent . That will trigger an injection to the fragment, not injection of fragment to the component. If you want to get the context of the activity from the fragment, you have to pass it to your module during initialization.

@Module
class FragmentModule(val fragment : Fragment) {
    @Provides
    fun provideContext(): Context = fragment.context!!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM