Yup, Providers are automatically injected too. But, injecting the "Injector" is considered bad behavior. A little-known but surprisingly useful interface called MembersInjector will better do what you want. You can change your Provider to inject a MembersInjector<T> into your Provider and then call membersInjector.injectMembers(instance). That way your provider is dependent just on the dependencies of T and not on everything in the Injector.
sam On Thu, Nov 4, 2010 at 1:57 AM, PhilBeaudoin <[email protected]>wrote: > I just did something and was surprised to see it work, so I thought of > posting it here to see if I could consistently rely on that behavior. > > I bind some class to a provider instance as such: > > bind(klass).toProvider(new SpyProvider(TypeLiteral.get(klass))); > > I need to have access to the Injector within SpyProvider so I @Inject > it in a field: > > public class SpyProvider<T> implements Provider<T> { > @Inject private Injector injector; > ... > } > > What I wanted to do at that point was to first create the injector and > then use injector.injectMembers(spyProvider) to fill-in the @Inject > field. I thought I needed that extra step since SpyProvider is > instantiated via new and should therefore not participate > automatically in dependency injection. > > However, I was surprised to see I could skip the injectMember() step > and the injected field would be automatically filled-in by Guice after > the call to Guice.createInjector(). Is this behavior expected and > documented? Can I rely on it? Does it happen only for providers or is > it also applied to toInstance() bindings? > > If you're curious about the codebase where this come from, it is from > the Jukito testing framework. The above lines are from: > > http://code.google.com/p/jukito/source/browse/src/main/java/org/jukito/TestModule.java#82 > and > > http://code.google.com/p/jukito/source/browse/src/main/java/org/jukito/SpyProvider.java > > Cheers, > > Philippe > > -- > 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]<google-guice%[email protected]> > . > For more options, visit this group at > http://groups.google.com/group/google-guice?hl=en. > > -- 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.
