【问题标题】:Dagger 2 Not injecting into dependant moduleDagger 2 不注入依赖模块
【发布时间】:2015-11-19 00:07:26
【问题描述】:

我检查了所有问题,但没有找到任何线索。我将我的问题简化为最简单的代码:

情况: 我想要:

    CatComponent catComponent = DaggerCatComponent.builder()
        .kameModule(new KameModule(MainActivity.this))
        .build();
   catComponent.getCatAnalyzer().analyze();

我已经创建了组件:

@Component(modules = {KameModule.class, CatAnalyzerModule.class})
public interface CatComponent {

    CatAnalyzer getCatAnalyzer();
}

和模块:

@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);
    }
}

和类:

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();
    }
}

当我从 CatComponent 检索我的 CatAnalyzer 对象时,它有 cat 字段 nulled。 我不知道为什么 Dagger 不会注入它。你能指导我吗?

【问题讨论】:

    标签: android module null inject dagger-2


    【解决方案1】:

    正确的代码:

    @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);
        }
    }
    

    感谢: https://www.future-processing.pl/blog/dependency-injection-with-dagger-2/

    【讨论】:

    • 您的@Inject 注释是多余的,因为您的CatAnalyzerModule 中提供了该类。你可以删除该模块,或者构造函数上的 @Inject 注释。无论哪种方式,KameCat cat 上的 @Inject 注释都是多余的。
    • 另外,对于更惯用的 DependencyInjection,KameModule@Provides 上下文,因此它可以参与任何模块中的任何位置。然后provideKameCat 方法也可以将Context 作为参数,类似于您对provideCatAnalyzer(KameCat cat) 所做的操作
    • 最后,如果您最终将两个模块都包含在@Component.modules 列表中,则不需要@Module.includes
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多