Document method and field injection, and MembersInjector
See original GitHub issueThe user guide states:
Dagger also supports method injection, though constructor or field injection are typically preferred.
However, I can find no example or explanation for the usage of this injection style, nor have my experiments yielded any working results. Is this supported? And if so how does one use it?
Simply annotating a public setter with @Inject
will cause a *_MembersInjector
class to be generated for that class but that MembersInjector
isn’t referenced anywhere else in the project or other generated classes so clearly it’s not “known” by the object graph.
Is method injection merely meant to provide a method of injection for something that otherwise (for whatever reason) couldn’t be injected via the constructor or via field injection? Maybe something that requires additional logic during injection? So the class with the method-injected setter must still be constructed via the object graph by, say, a Provider<T>
or something.
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
Thanks, that’s a fantastic summary.
We should add examples to the user’s guide.
In the meantime, here’s a quick summary. Let me know if this helps you for now.
If any methods or fields of a class
Foo
are annotated with@Inject
, then you can inject aMembersInjector<Foo>
and pass an instance ofFoo
to itsinjectMembers()
method, which will call those methods and set those fields. (You can actually inject aMembersInjector<Foo>
even if it has no@Inject
ed fields or methods; itsinjectMembers()
method will do nothing.)If
Foo
also has a constructor that’s annotated with@Inject
, then the factory forFoo
(Foo_Factory
) will actually use thatMembersInjector<Foo>
while providing instances ofFoo
. Try your example again where you annotate both a setter and the constructor, and you should see that the members injector is used.That’s the Dagger implementation. Now on to the use cases.
Field or method injection is useful for classes where user code (including Dagger) is not responsible for creating instances and/or constructors must not have parameters. A big example is Android classes like
Application
andActivity
, where the constructor must not take arguments, and the platform instantiates them.Field or method injection can also be useful in deep class hierarchies if you want to inject a dependency into a base class but you don’t want to make all subclasses add that dependency to their constructors—although in that case, you may see that as an opportunity to refactor to use composition instead of inheritance.