Search code examples
androidtddguiceroboguice

RoboGuice: method needs a new instance each call, injection possible?


If I want to make a new instance of an injected class each time, how do I do it? Here is the example that I am trying to do:

class Jet
{
  List<Missile> mAllMissiles;

  // 
  // make a new missile, and add it to the table.
  //
  void fireMissile()
  {
     Missile missile = new Missile();
     missile.doSomething();
     mAllMissiles.add(missile);
  }
}

Now, I can Inject the Missile, but wont it be the same missile each time? Is this a case where I need to inject the Provider?

http://code.google.com/p/google-guice/wiki/InjectingProviders

Or is there a different means of doing this?

Thanks.


Solution

  • Yes, inject a Provider<Missile>. If you can inject X, you can inject Provider<X>, and vice-versa. Injecting a Provider is the best way of requesting multiple instances of a class from the injector.