简体   繁体   English

Dagger 2不注入依赖模块

[英]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 . 当我从CatComponent找回我的CatAnalyzer对象有cat 清零场。 I have no idea why Dagger won't inject it. 我不知道为什么Dagger不会注射它。 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/ 感谢: https : //www.future-processing.pl/blog/dependency-injection-with-dagger-2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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