I think you need to add some injection calls to ObjectGraph #.
In each class where you have the @Inject annotation, you will also need to call the input method of the ObjectGraph that you created.
I also struggled with this for a while. I think the main template is:
- Annotate your fields to indicate that you want to enter them
- Create a module to "provide" instances for these @Injects
- Create a graph somewhere (most people seem to do this in the Application class)
- In the classes you want to enter from your module, get an instance of the graph and call inject (this).
I started using a singleton, not the Application class, because at least for the moment I have some places that I have to add to the application myself.
So, here is what I am doing now, that seems to work pretty weill
public class Injector { private static Injector mInjector; private ObjectGraph mObjectGraph; private MyApp mApp; private Injector() { } public static Injector getInstance() { if (mInjector == null) { mInjector = new Injector(); } return mInjector; } protected List<Object> getModules() { return Arrays.asList( new ApplicationModule(mApp), new AndroidModule(mApp) ); } public void inject(Object object) { getObjectGraph().inject(object); } public ObjectGraph getObjectGraph() { return mObjectGraph; } public void initialize(MyApp app) { mApp = app; mObjectGraph = ObjectGraph.create(getModules().toArray()); System.out.println(String.format("init object graph = %s",mObjectGraph.toString())); } }
Then in my application class I have a constructor like this:
public MyApp() { System.out.println("myapp construtor"); Injector.getInstance().initialize(this); Injector.getInstance().inject(this); }
Then when I want to add something, I do it
@Inject Bus mBus; public GcmBroadcastReceiver() { Injector.getInstance().inject(this); }
I have two modules: one for production and one for testing.
Manufacturing has this
@Provides @Singleton public Bus provideBus () { return BusProvider.getInstance(); }
and test has this
@Provides @Singleton public Bus provideBus () { return mock(Bus.class); }
source share