I am getting into Inversion of Control, specifically using Guice and RoboGuice for Android and I have a question.
I have a method call that returns a Resource (which is essentially an XML or JSON String).
public Resource getResource(){
// Some implementation details that call a web service and throw the result in a string...
String resource = ........
}
The Resource class is really just a wrapped String, so I figured it made sense to pass it in in the constructor, since it is an essential part of a Resource object.
public class Resource{
Resource(String theXMLorJSON){
...
}
}
A couple of questions:
- How do I construct a new
Resourcein thegetResourcecall? I would think that I want to use IoC and not callnewin the method. - If another class takes a
Resourcein the constructor, how can I use theGuicecontainer to construct it when I need a dynamicStringat construction time? I just asked a similar question and believe there may be a specific way to handle this usingGuice.
Thanks so much!
I think you may be misunderstanding something about dependency injection. You don’t need to try to avoid using
newin all cases… you primarily want to avoid usingnewto create anything that you might want to be able to mock out for testing, and it’s generally best to allow the container to wire up any class that depends on such an object.Your
Resourceclass, though, sounds like a simple value object that you can easily create manually in any testing you do. It also doesn’t depend on any kind of services… it just contains aString. So there’s no reason to try to have the container create it.The class containing the
getResource()method, on the other hand, you definitely want the container to create, because you’d like to be able to use something that depends on that class in testing without having to actually call a web service.Note that if you have a class with a constructor that takes both dependencies you want injected by the container and parameters that are only known at runtime, you need to create an intermediate factory of some kind with a method that only takes the runtime parameters. With Guice you can automatically create such a factory from an interface using the Assisted Inject (not sure if that works with RoboGuice, but it’s easy to create such a factory implementation manually too).