Will this make the instance a singleton?

4 views
Skip to first unread message

LoneWolf

unread,
Jan 27, 2008, 8:29:35 AM1/27/08
to google-guice
Hi.
Consider this module:
[code]
public class MyModule implements Module {
public void configure(Binder binder) {
// Bind Bar to an instance of Bar.
Bar bar = new Bar();
binder.bind(Bar.class).toInstance(bar);
}
}
[/code]
Does the previous code mean that Bar bar reference will be a singleton
and Guice will inject it into each object has dependency on Bar
object?
Thanks.

Robbie Vanbrabant

unread,
Jan 27, 2008, 9:48:16 AM1/27/08
to google...@googlegroups.com
You could think of this as a singleton. But:
- This rules out constructor injection
- You're bypassing Guice's real scoping mechanism
- Doing work in modules not related to configuration itself is a bad practice.

You should consider using asEagerSingleton or in(Singleton.class) instead.
IMO, the only valid use for toInstance is binding constants (to get some extra help from the compiler)

Robbie

Sam Berlin

unread,
Jan 27, 2008, 11:36:03 AM1/27/08
to google...@googlegroups.com
> You should consider using asEagerSingleton or in(Singleton.class) instead.
> IMO, the only valid use for toInstance is binding constants (to get some
> extra help from the compiler)

Another very good use for toInstance is binding mock objects in tests.
(Especially if Guice is hacked up to support overriding bindings.)

Sam

Reply all
Reply to author
Forward
0 new messages