Dagger2 - Project Rebuild Error - Field Injection - Android

假装没事ソ 提交于 2019-12-02 09:23:55

As you can see I commented Constructor Injection in HomePresenter. I'm having Field Injection there instead.

If you use Constructor Injection, then Dagger will create the object for you and know all about it.

If you use field injection then you have to create the object and tell Dagger about it.

I don't see why you would prefer to use field injection in this case, but with field injection you need to add a @Provides annotated method to one of your modules to give Dagger access to your presenter.

You need to use either Construcotr injection, or a @Provides annotated methods in your module, just as the error states.

You're confounding dependencies producer mechanism and dependencies consumption mechanism. An annotated field is used to consume a dependency. In your case, @Inject HomePresenter homePresenter is telling Dagger "hey, I want you to inject an HomePresenter here". To do so, Dagger either needs you to define a @Provides method or to have the object constructor annotated with @Inject.

As a rule of thumb, always use @Inject annotated constructor to provide dependencies. You should only use @Provides method provider when the objects you're providing are either:

  • an interface
  • an abstract class
  • an object coming from an external library (you don't have access to the constructor)
  • an object which requires customization before being provided

In your case, you got your error because you don't have a @Provides annotated method nor an @Inject annotated constructor. You should uncomment your constructor as it is the way to go in your situation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!