Recently I started looking at Inversion of Control technique using Dependency Injection. In Java there is a great tool called Google-Guice. This tool is great for creating more testable, modular code. There is a porting to Google-Guice in Android called RoboGuice. This is what I am going to write about here.
Since we (Conduit Mobile) write a platform, our Android and iOS code needs to be designed properly. This means heavy use of design patterns and coding techniques most application developers seldom use (at least to my knowledge – no offence guys). This approach lead me to consider IoC. Since we want our modules to be interchangeable and testable, IoC is a good way to go. When coming to implement it, I came to a dilemma – should I implement it myself, or should I use an existing library. One of the biggest changeless in IoC in Android is the need of Context in many of the objects. RG solved it quite nicely with a neat annotation mechanism.
Contexts and Singletons
I wanted to create a singleton in my app that should depend on the Application Context. The problem is that this context is only available when the app starts. I wanted to avoid bootstrapping the object (some init function that receives a context as parameters). I also don’t like all the repetitive code of the Singleton design pattern. In RoboGuice they solved these stuff using the @ContextSingleton annotation. Sadly, the documentation is behind the code, but after playing with it, it is quite a nice way to implement this. All you need to do is this:
- Make your singleton with Context be annotated with the @ContextSingleton annotation.
- In the singleton, inject the context using the @Inject annotation.
- Make your Activity/Fragment extend the RoboActivity/Fragment.
- Inject the singleton using the @Inject annotation.
So, for example:
The RoboActivity will take care of injecting the activity context. You can specify the exact context you want by changing this code a bit and instead of injecting the context directly, use the @Inject on a constructor that accepts a context and get the application context. e.g:
RG also have tons of other cool features that can be useful (View/Resource injection). I plan on using RoboGuice and see how it turns out. Hope I’m not heading for a fall, but it seems better than implementing it all myself.