Mixing scopes with Providers: RequestScoped & Singleton

1,384 views
Skip to first unread message

Jonathan

unread,
Apr 19, 2010, 7:31:06 AM4/19/10
to google-guice
Throughout the Guice docs it says the way to mix scopes is with a
provider, but I've not found any concrete examples on how to do it.
I'm not sure my solution is the best/cleanest way, so I'd appreciate
some advice.

I have a servlet annotated as @Singleton, and a Provider<Foo> that I'm
injecting into the servlet's constructor. A Foo is generated based on
information in the current ServletRequest.

Inside Provider<Foo> I've got my get() method, and I've got a static
inner class marked @RequestScoped that generates my Foo:

class FooProvider implements Provider<Foo> {
@Inject Injector injector;

@RequestScoped
static class FooMaker {
HttpServletRequest request;

@Inject
public FooMaker(HttpServletRequest request /*etc.*/) {this.request
= request; }

public Foo makeFoo() { /* make myNewFoo */ return myNewFoo;}
}

@Override
public Foo get() {
return injector.getInstance(FooMaker.class).makeFoo();
}
}

Specifically, can I do away with the inner class? Thanks for your
help!

Jonathan

--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To post to this group, send email to google...@googlegroups.com.
To unsubscribe from this group, send email to google-guice...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.

Christian Edward Gruber

unread,
Apr 19, 2010, 8:07:39 AM4/19/10
to google...@googlegroups.com
Can I beg you not to do this, despite what others may suggest about how this is possible.  It's such a very bad practice that seems to be prevalent in guice (depend something of wide scope on something of narrow scope by depending on its provider).

I would recommend, instead, that you not put your code mostly in the servlet, but use the servlet to get some sort of action object which has the logic you were going to put on the servlet from the container, and make it request scoped if it depends on request-scoped things.  The servlet, then, is merely dispatch.  

Having a Singleton depend on something in the session is just a great way to make your code seem magical and failures less obvious.  

Christian.

On Apr 19, 2010, at 7:31 AM, Jonathan wrote:

I have a servlet annotated as @Singleton, and a Provider<Foo> that I'm
injecting into the servlet's constructor. A Foo is generated based on
information in the current ServletRequest.

Jonathan

unread,
Apr 21, 2010, 7:28:01 AM4/21/10
to google-guice
Thanks very much for your advice, Christian. I'll try the refactoring
and see how it works out.

Cheers,
Jonathan

On Apr 19, 1:07 pm, Christian Edward Gruber <cgru...@google.com>
wrote:
Reply all
Reply to author
Forward
0 new messages