Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone provide a good explanation of Dagger 2?

Tags:

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 ?

like image 613
user47376 Avatar asked Nov 29 '15 11:11

user47376


1 Answers

@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:

  • Tasting Dagger 2 on Android by Fernando Cejas
  • Dependency Injection with Dagger 2 (Devoxx 2014) by Jake Wharton
  • Dependency Injection with Dagger 2
  • Dependency injection with Dagger 2 - the API by froger_mcs
  • Dependency injection with Dagger 2 - Custom scopes by froger_mcs

I guess it will help to understand.

like image 120
ArtKorchagin Avatar answered Sep 28 '22 01:09

ArtKorchagin