I have simplified my application to get the root of the problem and here is the simplified version. I'm implementing Dagger 2 using following configuration:
AppComponent
@Component(modules = [
AndroidSupportInjectionModule::class,
ActivityBindingModule::class
])
interface AppComponent: AndroidInjector<MyApp> {
@Component.Builder
interface Builder{
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
}
ActivityBindingModule
@Module
abstract class ActivityBindingModule {
@ContributesAndroidInjector
abstract fun mainActivity(): MainActivity
@Module
companion object{
@JvmStatic
@Provides
fun provideString(mainActivity: MainActivity): String{
return "Tent"
}
}
}
MainActivity
class MainActivity : DaggerAppCompatActivity() {
@Inject
lateinit var string: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
println("meco simplest ${string}")
}
}
When I run the application I get the following error. What I don't understand is ContributesAndroidInjector
is already providing an instace of MainActivity
why Dagger still complains about it.
MainActivity cannot be provided without an @Inject constructor or an @Provides-annotated method
EDIT for @yavor
Keep all classes as is and separate ActivityBindingModule implementation into two classes. Now you can see that instance of the MainActivity
is provided and Dagger is not complaining about it.
ActivityBindingModule
@Module
abstract class ActivityBindingModule {
@ContributesAndroidInjector(modulese [StringProviderModule::class])
abstract fun mainActivity(): MainActivity
}
StringProviderModule
@Module
class StringProviderModule {
@Module
companion object{
@JvmStatic
@Provides
fun provideString(mainActivity: MainActivity): String{
return "Tent"
}
}
}