简体   繁体   中英

Dagger 2 Not injecting into dependant module

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM