I am just beginning with dagger and came across some issues with singleton objects.
So the Singleton looks like this:-
@Module(
injects = {MainActivity.class,SecondActivity.class}
)
public class MySingle {
//just to count the number of instances of the class
public static int thecount=0;
//the constructor
public MySingle(){
Log.v("testing","created");
thecount++;
}
@Singleton
@Provides
public MySingle getSingle(){
return new MySingle();
}
}
The Application class where the object graph is created :-
public class MyApplication extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate(){
super.onCreate();
objectGraph=ObjectGraph.create(new MySingle());
}
public ObjectGraph getObjectGraph(){
return objectGraph;
}
}
The MainActivity.class:-
public class MainActivity extends ActionBarActivity {
@Inject MySingle mysingle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// MyApplication app=(MyApplication)getApplication();
// app.getObjectGraph().inject(this);
Log.v("testing", mysingle.thecount + " mainact");
}
}
So whenever I run this, the number of instances of the singleton "MySingle" is 1 , which is fine. However when i uncomment these lines:-
MyApplication app=(MyApplication)getApplication();
app.getObjectGraph().inject(this);
I get the number of instances as 2. I understand from herethat Dagger creates a singleton for every object graph , but from what I understand by using the above 2 lines, I am injecting MainActivity.class into the existing object graph, obviously the use of which is not apparent to me as of now.. i am just experimenting with it.