Bind interface to implementation without boilerplate
See original GitHub issueSometimes, for architectural reasons, I have interfaces with only one concrete class implementing them. Writing @Provides
methods for these cases can involve a lot of boilerplate, especially if the constructor has a lot of dependencies.
e.g.
@Provides
@ActivityScope
public FavouritesListContract.Presenter provideFavouritesListPresenter(FavouritesClient favouritesClient,
SearchStorage searchStorage, SettingsStorage settingsStorage, GoogleAnalyticsHelper googleAnalyticsHelper) {
return new FavouritesListPresenter(favouritesClient, searchStorage, settingsStorage, googleAnalyticsHelper);
}
As long as the concrete implementation has an @Inject
constructor it ought to be possible to just bind the class to the interface.
My thinking is that the binding still belongs in a Module
. Perhaps a list of bindings could be provided in the @Module
annotation?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:1
- Comments:9
Top Results From Across the Web
Inject interfaces without provide methods on Dagger 2 - Medium
If you have provide methods which just call constructor of implementation classes to inject interfaces, use @Binds annotation instead to get rid of...
Read more >Avoiding boilerplate in Java interfaces - enums - Stack Overflow
I'm mostly trying to get around the fact that enums only let you implement interfaces while I'd like an enum that extends an...
Read more >Dagger dependencies beyond the basics | by Fabio Collini
A Binds annotated method contains a parameter with the implementation and declares the return type as the interface, the body is not necessary ......
Read more >3 Reasons to Use Interface That Only One Class Implements
Yes, setting up interfaces for classes without alternate implementation consumes time and effort. But with their lightweight and simple boilerplate, how much ...
Read more >Inject vs Provides vs Binds in Dagger and Hilt
Use @Binds for injecting interfaces while generating less DI code. @Inject. Using classes with @Inject annotated constructors should be your ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Yes, we are working on a feature that will let you do exactly that.
In the meantime, if
FavouritesListPresenter
has an@Inject
constructor, this formulation is equivalent and much more brief:Dagger 2.4 has been released, check out @Binds!