Reputation: 1
I have a FooViewModel
that is scoped to the FooFragment
. In FooFragment
, the device type is passed from another fragment based on what user selects. I want to inject this in the constructor of the FooViewModel
. How should I provide the deviceType
in the module?
Here's my setup -
@Module
interface FooModule {
@ContributesAndroidInjector
fun contributesFooFragment(): FooFragment
companion object {
@Provides
fun provideDeviceType(fragment: FooFragment) = fragment.deviceType
}
}
I get an error
[Dagger/MissingBinding] FooFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
...
Upvotes: 0
Views: 27
Reputation: 11
the error message is indicating that Dagger can't provide an instance of FooFragment because it doesn't have an @Inject constructor or a @Provides-annotated method that returns an instance of FooFragment.
The issue is that you're trying to contribute FooFragment to the Android injector using @ContributesAndroidInjector, but you're not providing a way for Dagger to create an instance of FooFragment.
To fix this, you need to provide a way for Dagger to create an instance of Foo Fragment One way to do this is by adding an @Inject constructor to
class FooFragment @Inject constructor() : Fragment() {
}
By adding an @Inject constructor, you're telling Dagger that it can create an instance of FooFragment using this constructor.
Alternatively, you can provide a @Provides-annotated method that returns an instance of FooFragment
@Module interface FooModule {
@ContributesAndroidInjector
fun contributesFooFragment(): FooFragment
companion object {
@Provides
fun provideFooFragment(fragmentManager: FragmentManager): FooFragment{
return FooFragment()
}
}
}
In this example, the provideFooFragment method provides an instance of FooFragment using the FragmentManager.
Once you've added one of these solutions, Dagger should be able to provide an instance of FooFragment and the error should be resolved.
Upvotes: 0