tann36
tann36

Reputation: 109

Dagger 2 dependencies in non-activity classes

So there are many-many tutorials that show how to have a dependency injected into an activity class using Dagger 2. But for some reason dependencies never seem to be inserted into classes that aren't activities/fragments/services. I would like to know how to insert dependencies into a normal class.

Right now, I'm trying to have dagger inject into a field, but the field remains null. I'm assuming the mistake is that I'm not telling dagger to do its injecting. But I'm not sure how to resolve this.

@Module
public class TestModule {
    @Provides 
    @Singleton
    String provideTestString() {
        return "test string";
    }
}
@Singleton
@Component(modules = { TestModule.class })
public interface TestComponent {
    void inject(TestClass testClass);
    String getTestString();
}
class TestClass {
    @Inject
    String testString;

    public boolean isTestStringNull() {
        return testString == null;
    }
}
Log.d("---", "is test string null: " + new TestClass().isTestStringNull());//is true

While I may call DaggerTestComponent.create() in a subclass of Application, it won't be available inside random classes that don't know about Application. So what is the correct way to get dagger to initialize my field?

Upvotes: 2

Views: 1140

Answers (2)

Mike
Mike

Reputation: 2705

Every application has an entrance. So instead of Application, you can use some top-level class. The approach is similar to one with Activity or even easier because you can pass required classes into a constructor.

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81578

class TestClass {
    @Inject
    String testString;

    @Inject
    TestClass() {}
}

@Singleton
@Component(modules = { TestModule.class })
public interface TestComponent {
    TestClass testClass();

    String testString();
}

Log.d("---", "is test string null: " + component.testClass().isTestStringNull());//is false

Upvotes: 2

Related Questions