Michael Ekstrand
Michael Ekstrand

Reputation: 29090

Scoped providers in Guice

Does scoping work on Guice providers? Suppose I have a FooProvider and bind like thus:

bind(Foo.class).toProvider(FooProvider.class).inScope(ServletScopes.REQUEST)

Will the FooProvider be instantiated once per request?

Upvotes: 4

Views: 1839

Answers (2)

jfpoilpret
jfpoilpret

Reputation: 10519

No, FooProvider will be instantiated by Guice only once.

The scope applies to the binding, which means in your example that, if Foo is injected into another REQUEST-scoped object, Guice will call FooProvider.get() and will inject the returned Foo into that original object.

If you want the scope applied to FooProvider, then you would have to do something like that (NB: I haven't checked it but it should work):

bind(FooProvider.class).in(ServletScopes.REQUEST);
bind(Foo.class).toProvider(FooProvider.class).in(ServletScopes.REQUEST);

Upvotes: 4

Waldheinz
Waldheinz

Reputation: 10487

It should be

bind(Foo.class).toProvider(FooProvider.class).in(ServletScopes.REQUEST);

but otherwise this should work as expected.

Upvotes: 6

Related Questions