Allow @AssistedInject objects to be injected and provided by @Provides methods
See original GitHub issueI got some singleton/reusable, expensive-to-create-and-update key-value/preference objects in my app that I create by calling factory methods from @Provides
methods. I’d think it’s a common and valid pattern, but not possible with @AssistedInject
. I can work around it with ease, but every time I come across my hand-coded factory I wonder why it has to be there. I have to add code comments to explain and defend the design flaw.
This is what I’d like to do:
class ValueCache @AssistedInject constructor(repository: Repository, @Assisted key: String) {
@AssistedFactory interface Factory {
fun create(key: String): ValueCache
}
}
// In some module...
@Provides @Reusable @Named("LikesRed") fun provideUserLikesRedCache(cacheFactory: ValueCache.Factory):
ValueCache = cacheFactory.create("userLikesRed")
@Provides @Reusable @Named("LikesGreen") fun provideUserLikesGreenCache(cacheFactory: ValueCache.Factory):
ValueCache = cacheFactory.create("userLikesGreen")
Dagger does not support providing @AssistedInject types
Dagger does not support injecting @AssistedInject type
If I understand correctly, it’s essentially an arbitrary restriction in this specific case to dumb things down for inexperienced users in the general case. It violates API orthogonality in the specific case. There are various precursors in Dagger doing similar handholding restriction things, and they are generally a hard pill to swallow for an experienced user wanting to write clean, low-boilerplate code; I wish Dagger was generally maintained with less bias toward disallowing things.
A flag to disable the restriction could perhaps address the issue while maintaining the restriction in the general case, like an annotation parameter: @AssistedInject(allowInjection=true)
. Or a compile flag to disable the restriction in general, at the cost of letting me shoot myself in the foot. I prefer that, though, over having cluttered code.
Issue Analytics
- State:
- Created 3 years ago
- Comments:8
Top GitHub Comments
I also experienced this issue when attempting to migrate from Jake’s original AssistedInject library which allowed this pattern to the Dagger integrated version. Good to know a fix is coming, thanks!
Adding an artificial annotation at every injection site is polluting, and easily missed; this is one benefit of custom types, less pollution, fewer errors. Writing a custom factory is a thousand times preferable over carrying around nonsensical annotations. It hurts my brain to consider such a thing.
You got the use case. You got the blueprint library behavior in front of you. You got more practical frameworks taking over. I guess that’s not enough to change Dagger’s ways.