Binds annotation for scoping dependencies
See original GitHub issueFrequently in our applications, we would like to apply a scope annotation to a class, and given that most of the time constructor injections is perfectly appropriate for binding resolution, the scope annotation must go elsewhere.
It’s not desirable to have a scope annotation on the implementation of the class, as this confuses the how to the why, so we must use an annotation in a module, often mimicking the required constructor injection.
class OfferRepository(OfferCache cache) { ... }
@Module
class OfferModule {
@Provides
@PerActivity
OfferRepository offerRepository(OfferCache offerCache) {
return new OfferRepository(offerCache);
}
}
Alternatively, it would be nice to be able to apply a @Binds
annotation similar to how you would for an interface implementation, but simply just for the class via constructor injection.
For example
class OfferRepository {
@Inject
OfferRepository(OfferCache offerCache) { ... }
}
@Module
abstract class OfferModule {
@Binds
@PerActivity
abstract OfferRepository offerRepository()
}
I had thought to try abstract OfferRepository offerRepository(offerRepository: OfferRepository)
as a proposal but this seems a bit too verbose, and returning this value with a @Provides
annotation unsurprisingly causes a cyclical dependency cycle.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:6
Top GitHub Comments
I remember this being discussed multiple times. I think it is just about being more flexible and giving people options. If you have a base interface, then you need to use
Binds
in a module and that is where you can put the scope annotation. So why not give the possibility/flexibility to declare scopes also in the module for constructor injected concrete classes.@ronshapiro potentially, as I mentioned it might be acceptable to simply use a scope alias indicating that the class contains state, a common use case I would imagine since performance based persistence can typically rely on
@Reusable
.But primarily its the concern that the class shouldn’t be responsible for specifying its own scope, in the same way that an injection target shouldn’t be responsible for its own injection.