如何使用Dagger2将ApplicationContext注入非活动类?

Le2*_*410 2 android dagger-2 android-application-class

我有几个我想注入的课程.例如,我有一个APIContentLoader类,用于从端点下载JSON,然后将其存储到数据库中.我想将我用于读/写数据库的DatabaseManager类注入到APIContentLoader中.为了将DatabaseManager注入此类,我首先需要对ApplicationContext的引用,对吗?

这就是我现在设置的方式:

public class APIContentLoader{
    @Inject DatabaseManager dbm;
    @Inject BaseApplication app;

    public APIContentLoader(){
        app.getAppComponent().inject(this);
        // dbm now is ready for use
    }  
    ... // rest of class stuff
}
Run Code Online (Sandbox Code Playgroud)

我的BaseApplication类扩展了标准的Application类.以这种方式向这个类注入BaseApplication引用是不好的做法?我知道对ApplicationContext进行静态引用并不是将它们提供给这些非活动类的好方法.

我想最重要的问题是,这种方法是否存在与内存管理相同的静态引用问题,并持续存在这些辅助类的生命周期?

Kev*_*ede 6

这就是我对你的课程实际上是什么的问题所得到的:

Android组件(活动,服务等)受益于依赖注入,因为它们需要一个无参数构造函数,因此框架可以创建它们的实例.未由Android框架实例化的类应该只接收其作为构造函数参数的依赖项.没有理由@Inject在这样的课程中有字段.