Feature request: factory method in components for assisted injection
See original GitHub issueIt is a common case when a class have some dynamic parameters along with usual dependencies.
For example articleId
is a dynamic parameter whereas articleService
is an usual dependency.
class ArticlePresenter {
...
ArticlePresenter(long articleId, ArticleService articleService) {
...
}
}
This mixing of parameters and dependencies is known as Assisted injection. Dagger 2 does not support this feature now.
There are three work-around known to me:
- Use factories (probably generated by third-party libraries).
- Create a separate component for a class with dynamic parameters.
- Set dynamic parameters with setters after an object is created.
In my opinion, all of these aproaches are far from ideal. So I propose a new feature “Factory method in components” for support of assisted injection.
Lets allow components to have getSomething
methods with parameters. Like that:
@Component
public interface AppComponent {
ArticlePresenter getArticlePresenter(long articleId);
}
Add @Param
annotation to specify which constructor arguments are dynamic parameters:
@Inject
public ArticlePresenter(@Param long articleId, ArticleService articleService) {
...
}
After that we can request objects from the component:
ArticlePresenter presenter = appComponent.getArticlePresenter(someId);
Of course, this is just an idea not a complete solution. What do you think, guys? Will it make Dagger 2 even more awesome?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:24
- Comments:5
Top GitHub Comments
I’ve been thinking about this problem a lot, mostly in the context of two concepts:
Provider
objects for each dependency - fine for servers, but bad in client apps.I think Dagger could provide a nice intermediary and we could design something that was still JSR 330 compatible (and easy to use within Guice, Spring, etc). The Dagger flavor could take advantage of the inlining work we’ve done recently and be a much lighter weight factory.
The one downside in my current design is the factory would hold an implicit reference back to the component and could be a memory leak. But there’s more to think about this. I’ll post back when I’ve thought about it more.
@cgdecker is working on something like this