Reputation: 261
I checked all questions but did not find any clue. I stripped my problem to a simplest code:
Situation: I want to have:
CatComponent catComponent = DaggerCatComponent.builder()
.kameModule(new KameModule(MainActivity.this))
.build();
catComponent.getCatAnalyzer().analyze();
I have created component:
@Component(modules = {KameModule.class, CatAnalyzerModule.class})
public interface CatComponent {
CatAnalyzer getCatAnalyzer();
}
And modules:
@Module
public class KameModule {
private Context context;
public KameModule(Context context) {
this.context = context;
}
@Provides
KameCat provideKameCat() {
return new KameCat(context );
}
}
@Module(includes = KameModule.class)
public class CatAnalyzerModule {
@Inject
KameCat cat;
@Provides
CatAnalyzer provideCatAnalyzer() {
return new CatAnalyzer(cat);
}
}
And classes:
public class KameCat {
Context context;
public KameCat(Context context) {
this.context = context;
}
public void doCatStuff() {
Toast.makeText(context, "Poo and Meow", Toast.LENGTH_LONG).show();
}
}
public class CatAnalyzer {
@Inject
KameCat cat;
@Inject
public CatAnalyzer(KameCat cat) {
this.cat = cat;
}
void analyze() {
cat.doCatStuff();
}
}
When I retrieve my CatAnalyzer object from CatComponent it has cat
field nulled.
I have no idea why Dagger won't inject it. Could you guide me somehow?
Upvotes: 3
Views: 1504
Reputation: 261
Proper code:
@Module(includes = KameModule.class)
public class CatAnalyzerModule {
@Inject //remove this
KameCat cat;// remove this
@Provides
// Add cat as a argument and let KameModule provide it..
CatAnalyzer provideCatAnalyzer(KameCat cat) {
return new CatAnalyzer(cat);
}
}
Thanks to: https://www.future-processing.pl/blog/dependency-injection-with-dagger-2/
Upvotes: 4