Alek KT
Alek KT

Reputation: 154

Dagger2 Architecture failed with .Application does not implement dagger.android.HasAndroidInjector

I'm learning Dagger2 and I'm trying to build a very dumb example (Mainactivity have to instantiate a Car class).

And I have to handle with this error .Application does not implement dagger.android.HasAndroidInjector

if I've understood correctly :

  1. my component need to be annotated @Component and have to reference my module @Module ( with some methodes annotated @Provides)
  2. I have to use the lateinit var to instantiate my class and use the annotation @Inject.

Where I failed?

My MainActivity:

class MainActivity : DaggerAppCompatActivity() {

    @Inject
    lateinit var car: Car

    public var brand: String = "Peugeot"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        DaggerAppComponent.builder().application(application).buildAppComponent()
        car.name = brand


        Log.e("CarText", "onCreate: ${car.name}")
    }

My AppComponent

@Component(
    modules = arrayOf(AppModule::class)
)
public interface AppComponent : AndroidInjector<AppComponent>{

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun buildAppComponent(): AppComponent
    }

My AppModule

@Module
class AppModule {

    companion object{
        @Provides
        fun createCar(): Car {
            return Car("")
        }
    }


}

and to finish my car class

data class Car(var name: String)

Upvotes: 0

Views: 1271

Answers (1)

Alek KT
Alek KT

Reputation: 154

The solution have been found.

  1. I miss the AndroidSupportInjectionModule::Class in my AppComponent
  2. I miss to create an abstract Method with the annotation @ContributesAndroidInjector in my APP module

Upvotes: 0

Related Questions