What else Dagger 2 injection provides?
Published in
3 min readOct 16, 2019
Many a times, we just use Dagger 2 to inject dependencies. But it could provides more than that. Take for example the below code
class Dependency @Inject constructor()
@Component
interface MainComponent {
fun inject(target: Target)
}
We think we could only get the Dependency
object injected. But it also could provides the Provider<Dependency>
and Lazy<Dependency>
.
class Target {
@Inject
lateinit var dependency: Dependency
@Inject
lateinit var dependencyProvider: Provider<Dependency>
@Inject
lateinit var dependencyLazyProvider: Lazy<Dependency>
init {
DaggerMainComponent.builder().build().inject(this)
}
}
Both Provider
and Lazy
could be used to generate Dependency
object.
The question is, are they the same copy generated, or different copies generated each time?
Generation of Provider/Lazy and its dependencies
Assume we instantiate 2 target objects code, where each has their own set of Dependency
, Provider
and Lazy
val target1 = Target()
val target2 = Target()