Hi,
Sometimes it can be very convenient to just do
injector.getInstance(InjectedObject.class), for instance if you have a
object you don't need to be able to mock, but want to send a
dependency that you _would_ be like to be able to mock[1]. Currently I
do this by setting a global reference to the Injector when my module
is set up (typically either in a junit setUp() or extending
GuiceServletContextListener, see bottom for the code for the
latter[2]).
Is this considered bad practice? If so, (a) what is the kosher way?
and (b) any practical consequences?
Also, a somewhat related question: Instead of doing the assisted
inject hoopla (which Guice admittedly makes much much more elegant
than manual factories), I sometimes find it easier to do:
new NonInjectedObject("param that could have been annotated
assisted",
injector.getInstance(InjectedObject.class));
Will this be frowned upon by you DI gurus? :-)
Cheers,
-S-
[1] - For example for some simple ad-hoc JSPs, I have a JSPFacade
class that will never be anything else, but it is indeed useful to
switch the implementations it uses or at least get all the
dependencies autowired according to the active module config.
[2] - Code for global reference in the guice servlet context listener:
/** Don't know if this is bad practice, but sets up and keeps a
global reference that can be used to use the Injector other places. */
public static Injector getGlobalInjectorReference(){
return injector;
}
@Override
protected Injector getInjector() {
injector = Guice.createInjector(new ServletModule() {
@Override
protected void configureServlets() {
log.info("configureServlets starting");
....
}
});
return injector;
}
--
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.