2010/1/8 Andrey <[email protected]> > Hello! > > How can I make Guice create singletons by default? > > At the moment ALL my classes are injected as singletons so if it was > default scope I could remove all such lines from the module: > > bind(ProductsController.class).in(Singleton.class); > bind(ProductService.class).in(Singleton.class); > ... > > Look at the Spring for example - singleton is the default scope in > Spring and it is correct, because we usually use injection for high > level services, controllers and other singletons. If we need new > instance every time we just use new, we do not usually need IOC for > that. So it is very strange for me that Guice's default scope is > "new". >
The default scope is "no scope", ie. provide a new instance on each request
imho this is a cleaner default because singletons, request and session
scopes,
etc. can all be implemented as separate layers on top of the default
behaviour:
bind(ProductsController.class)
vs
bind(ProductsController.class).in(Singleton.class)
vs
bind(ProductsController.class).in(RequestScoped.class)
Can I change this?
>
Well as Jeremy said you could add @Singleton to the classes (which is
also a good hint to the developer to be extra careful about thread safety)
or you could write utility methods (or a custom module class) to simplify
your instructions - ie. what you normally do when you see duplicate code.
For example you could have a set of bindSingleton methods that map to
the appropriate "bind(...).in( Singleton.class )" calls.
Finally the Guice SPI lets you traverse module bindings - you could use
this to convert a module (on-the-fly) with no-scope bindings into one that
has singletons as the default:
http://code.google.com/p/google-guice/wiki/ExtendingGuice
# see the Module and Elements javadoc
HTH
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]<google-guice%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/google-guice?hl=en.
>
--
Cheers, Stuart
-- 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.
