2

I have a @Module class that has many @Provides methods. My @Component takes a dependency on this Module class. Ex:

@Singleton
@Component(modules = { MyModule.class})
public interface MyComponent {

    ObjectA getObjectA();

    ObjectB getObjectB();

}

@Module
public class MyModule {

    @Provides
    @Singleton
    ObjectC provideObjectC() {
        return new ObjectC();   
    }

    @Provides
    @Singleton
    ObjectD provideObjectD() {
        return new ObjectD();   
    }

    @Provides
    @Singleton
    ObjectA provideObjectA(ObjectC objectC) {
        return new ObjectA(objectC);    
    }

    @Provides
    @Singleton
    ObjectB provideObjectB(ObjectD objectD) {
        return new ObjectB(objectD);    
    }
}

I create an instance of the component using the Dagger builder, and provide a new instance of MyModule. If I only call myComponent.getObjectA() will it also construct ObjectB (and its dependencies), or are those left unconstructed?

emilyk
  • 713
  • 5
  • 14
  • 26

2 Answers2

4

Ran a manual test of the code I provided in the question with logging. If your injection only uses ObjetA, it will create ObjectA and ObjectC, but it will not create ObjectB or ObjectD.

emilyk
  • 713
  • 5
  • 14
  • 26
  • Just so you know, the code you provided doesn't really follow the standard practices of using Dagger. You shouldn't be manually calling provider methods. – Austin Hanson Nov 27 '17 at 14:04
  • I've updated the question to reflect that and to avoid future confusion as the question wasn't actually about the injection of the objects but about the objects that are completely unused. – emilyk Nov 28 '17 at 00:09
0

It's been a while since I've used Dagger but you should specify those as parameters in the provide statement for it to work correctly. It will manage calling your other provider methods to grab the singleton instances.

@Provides
@Singleton
ObjectB provideObjectB(ObjectD objectD) {
    return new ObjectB(objectD);   
}

Or else you can also specify it as an injected constructor. See Dagger 2 injecting parameters of constructor

Austin Hanson
  • 21,820
  • 6
  • 35
  • 41
  • Thanks, but that doesn't quite answer what I was looking for in the question. Even with that pattern, will it construct the objects that don't get called on the Component interface? – emilyk Nov 21 '17 at 20:57
  • Yes, sorry, I should have been more clear. It will handle, internally, calling your other provider functions. – Austin Hanson Nov 22 '17 at 18:16