On Monday, November 12, 2012 10:55:32 PM UTC+1, Alper Akture wrote:
>
> I'm using a game server that instantiates objects (Event handlers, etc)
> that I would like to inject references into. Since they construct these
> instances, is there an approach other than doing something in a default
> constructor like this to inject those dependencies?
>
> public class MyHandler {
> MyInectedClass myInjectedObj;
> public MyHandler() {
> myInjectedObj =
> MyInjector.getInstance().getInjector(MyInjectedClass.class);
> }
> ...
> }
>
In cases where I cannot have my classes instantiated by Guice (in my case,
more specifically GIN, but the patterns apply to Guice too), I use
requestStaticInjection in my module to inject a static
Provider<MyInjectedClass> inside the MyHandler class, then in the MyHandler
constructor I .get() the provider to initialize the instance fields:
public class MyHandler {
@Inject private static Provider<MyInjectedClass> myInjectedProvider;
private final MyInjectedClass myInjectedObj;
public MyHandler() {
myInjectedObj = myInjectedProvider.get();
}
}
Not much "cleaner" (if any), but thought I'd share anyway; it frees you
from exposing the Injector, so you can keep it private to your entry-point
(main(), ServletContextListener or whatever)
--
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/google-guice/-/olUtSc1rVwYJ.
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.