On 11/04/2010 23:35, Piotr Sobczyk wrote:
We are developing project that uses guice. That's how we have worked
until now:
If we needed single instance some dependence in class A then we
naturally injected it in normal way through constructor or setter:
public class A{
private B b;
@Inject
public A(B b){
this.b = b;
}
public void INeedToUseSingleInstanceOfB(){
b.use();
}
}
But if we needed multiple instances of dependent class, than we did
like that:
public class A{
public void INeedEveryTimeNewInstanceOfB(){
B b = Guice.createInjector(new MyModule()).getInstance(B.class);
b.use();
}
But now I notced that all our singletons (objects in Guice Singleton
scope) doesn't work as excpeced. After some reading I realized that
object is treated as singleton only for single Injector and we are
using a log of different injectors in our code (creating new in many
places).
Correct. :)
What is the best solution:
1. To make only one use of injector in main() method:
public static void main(){
A a = Guice.createInjector(new MyModule()).getInstance(A.class);
}
And do not create new injectors in other classes but have everything
injected recursively beginning from class A. And for multiple
instances of Guice-managed class use Providers that return new object
in every get method? (We've started to follow that path).
That's definitely the way to go.
2. To create singleton (global) Injector as standard Java Singleton:
public class InjectorHolder{
private static Injector injector = Guice.createInjector(new
MyModule());
public static getInjector(){return injector;}
}
And keep using injectors directly in various classes where we need to
create multiple instances of Guice-managed class (that would require a
lot less of work and refactoring from current state of code base).
You should never (!!!) need to use the Injector directly. Having it in a
static field seems extremly
awkward to me. If you really need it somewhere (e.g. dependencies which
are only known at runtime)
you can inject the Injector via @Inject.
Hope that helped.
3. Create custom scope that treats singleton as singleton regardless
of Injector being used? Is It possible?
What is the best solution from above and what are it's advantages over
others? Or maybe there are other ways?
Thanks in advance.
--
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-guice?hl=en.