Dagger 2 injection in non Activity Java class
You should generally use constructor injection whenever possible. The call to component.inject(myObject)
is mostly to be used for objects which you can not instantiate yourself (like activities or fragments).
Constructor injection is basically what you already did:
private class MyManager {
private SharedPreferencesManager manager;
@Inject
MyManager(SharedPreferencesManager manager){
this.manager = manager;
}
}
Dagger will create the object for you and pass in your SharedPreferencesManager
. There is no need to call init or something similar.
The real question is how to obtain an object of MyManager
. To do so, again, dagger will handle it for you.
By annotating the constructor with @Inject
you tell dagger how it can create an object of that type. To use it, just inject it or declare it as a dependency.
private class MyActivity extends Activity {
@Inject
MyManager manager;
public void onCreate(Bundle savedState){
component.inject(this);
}
}
Or just add a getter to a component (as long as SharedPreferenceManager
can be provided, MyManager
can also be instantiated):
@Component(dependencies = SharedPreferenceManagerProvidingComponent.class)
public interface MyComponent {
MyManager getMyManager();
}