androiddagger-2android-application-class

How do I inject the ApplicationContext to a non-activity class using Dagger2?


I have several classes that I would like to inject to. For example, I have an APIContentLoader class I use for downloading JSON from an endpoint and then storing it to the database. I would like to inject the DatabaseManager class I made for reading/writing to the database into APIContentLoader. In order to inject the DatabaseManager into this class, I first need a reference to the ApplicationContext, correct?

This is how I have it setup right now:

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
}

My BaseApplication class extends the standard Application class. Is injecting the BaseApplication reference to this class in this manner bad practice? I know making a static reference to the ApplicationContext is not a good way to go about making it available to these non-activity classes.

I guess the big question is, does this approach present the same problems of a static reference as far memory management and persisting the lifespan of these helper classes?


Solution

  • This is what I'm getting at with my question about what your class actually is:

    Android components (activities, services, etc.) benefit from dependency injection because they require a no-arg constructor so the framework can create instances of them. A class that's not instantiated by the Android framework should simply receive its dependencies as constructor arguments. There's no reason to have @Inject fields in such a class.