I posted something about this a month or so ago:
http://groups.google.com/group/google-guice/browse_thread/thread/1418dfe59246f819/f7ed43be6b907ade
I wrote a scope doing just this, called LongTermScope, which I can
send you, but after I did it I decided I didn't like it. One issue I
found is that there's no guarantee that two objects you inject in this
scope are from the same generation, even if they are both parameters
to the same injected constructor. Another was that it didn't seem
possible to prevent injection of LongTermScope objects directly into
Singletons (they'd need providers).
I'd previously thought to use two provider bindings instead, and in
fact Sam Berlin recognized the use case (resettable settings) from the
proposed solution and suggested the provider bindings instead.
I've taken Sam's idea and use MutableProvider extends Provider, and
Resettable. These are used to wrap existing settings beans, which
themselves are grouped to guarantee generational consistency.
This seems to be working for me, and I do this
@Inject FooBean
for objects that are short-lived.
@Inject Provider<FooBean>
for objects that might span a generation.
@Inject MutableProvider<FooBean>
for resources that need to write to the bean
@Inject Resettable<FooBean>
for resources that simply need to assert that that the Bean has
changed (flush cache).
I've made two implementations of these MutableProviders: one that is
simply a singleton, and another than adapts to some existing RMI code,
for which I just call the super constructor with the parameters
necessary for the service location.
I've also made some helpful routines for binding in ab abstract class
called MutableProviders. (Unfortunately, Guice subsequently came out
with Providers.of with a different meaning so I may need to change
this name.)
static <T extends Object> TypeLiteral<MutableProvider<T>> of(Class
<T> x);
so you can do this
bind(beanClass).toProvider(beanProviderClass);
bind(MutableProviders.of(beanClass)).to(beanProviderClass);
additionally I found had to use the LazySingleton scope hack to avoid
the providers being activated too early:
bind(beanProviderClass).in(MoreScopes.LAZY_SINGLETON);
There's probably a cooler way to do it, but I just defined a method in
my Module to do this:
private <B extends Object, P extends MutableProvider<B>> void defBean
(Class<P> beanProviderClass, Class<B> beanClass)
which then does the three lines above.
If you need annotations, there's a MultibleProviders.of variant that
does that.
Maybe I'll stick this in pastie if there's sufficient interest. Or
maybe Sam already has something better worked out.
Leigh.