Using Dagger 2, I'm trying to inject a singleton object at multiple locations in a single scope. However, it seems my solution instead creates a new instance each time.
In this test project, I have a MainActivity which initializes the DaggerModule. The DaggerModule provides the objects Box and Cat, with Box taking Cat as a parameter. I also take in Cat in my MainActivity. Finally, I check the references of the both Cat variables injected (in the Box and in the MainActivity respectively), but they are not the same instance.
If I call provideCat() twice in my MainActivity instead, the same instance is provided.
MainActivity:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerModule daggerModule = new DaggerModule();
DaggerComponent daggerComponent = Dagger_DaggerComponent.builder()
.daggerModule(daggerModule).build();
// Same Cat instance returned.
Cat cat1 = daggerComponent.provideCat();
Cat cat2 = daggerComponent.provideCat();
Log.d("=== cat1: ", cat1.toString());
Log.d("=== cat2: ", cat2.toString());
// Different Cat instance returned. Why?
Box box = daggerComponent.provideBox();
Log.d("=== box cat: ", box.getCat().toString());
}
}
@Module
public class DaggerModule {
@Provides
@Singleton
public Cat provideCat() {
return new Cat();
}
@Provides
@Singleton
public Box provideBox() {
return new Box(provideCat());
}
}
@Singleton
@Component(modules = { DaggerModule.class })
public interface DaggerComponent {
Cat provideCat();
Box provideBox();
}
public class Cat {
@Inject
public Cat() {
}
}
public class Box {
private Cat mCat;
@Inject
public Box(Cat cat) {
mCat = cat;
}
public Cat getCat() {
return mCat;
}
}
Thanks in advance!
Edit: It works if provideBox takes in a Cat argument and uses that to create the Box, instead of calling provideCat directly from within provideBox.
// Doesn't work, new Cat instance created.
@Provides
@Singleton
public Box provideBox() {
return new Box(provideCat());
}
vs
// Works, same singleton injected.
@Provides
@Singleton
public Box provideBox(Cat cat) {
return new Box(cat);
}
What's the difference between calling provideCat in the MainActivity and doing it from within provideBox in the DaggerModule? Could it be that the Dagger compiler doesn't process the DaggerModule the same way it does with external classes and the annotations don't get applied if I call provideCat in there?