I'm really having a hard time understanding the Dagger 2 Dependency injection system.
I understand the use of the @Inject
annotation to tell Dagger we need to provide an instance of some type to here.
But, I don't understand the various roles of the other components such as: @Module
, @Component
, @Provides
and how they work together to provide the appropriate instance to the appropriate dependency.
Can someone please explain it simply and concisely ?
@Module: Modules are classes whose methods provide dependencies, so we define a class and annotate it with @Module, thus, Dagger will know where to find the dependencies in order to satisfy them when constructing class instances. One important feature of modules is that they have been designed to be partitioned and composed together (for instance we will see that in our apps we can have multiple composed modules).
@Component: Components basically are injectors, let’s say a bridge between @Inject and @Module, which its main responsibility is to put both together. They just give you instances of all the types you defined, for example, we must annotate an interface with @Component and list all the @Modules that will compose that component, and if any of them is missing, we get errors at compile time. All the components are aware of the scope of dependencies it provides through its modules.
@Provide: Inside modules we define methods containing this annotation which tells Dagger how we want to construct and provide those mentioned dependencies.
I advise you to read this:
I guess it will help to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With