简体   繁体   中英

Dagger2 initialization of components

I am implementing dependency injection using dagger;

and using injected classObject as follows,

CarComponent carComponent = DaggerCarComponent.create();
car=carComponent.getCar();

Now queries are,

  1. like we do in spring, by adding @Service/@Component to class, we dont required explicitly call something to init this object(like DaggerCarComponent.create() ) Spring will take care to init this service object to register in App context.
  2. In Consumer class do we every-time need to call DaggerCarComponent.create().getCar() to get Car Object? is there any other way?

Dagger-2 provides Android-specific support which we usually use to avoid to write a large number of boilerplate codes. You can more find out the dependencies here .

Answer 1
I'm not much familiar with Spring but when using dagger2 in Android we need to provide a way to construct all the dependencies in our Main Component. If we own the class we usually do Constructor Injection and then provide a provisioning method to get our class object. If we don't own the class then we need to make @Moduels and then @Provides their implementation then add that module to our Component so our components can use them and provides them when needed.

Answer 2
Never initiate the Component in every class, If you create a Component in every consumer class then what you're basically doing is creating a whole separate individual set of dependencies in every consumer class which will cost waste of memory because if a consumer class have only one dependency then instead of giving that dependency only we are giving all our dependencies

What we usually do we initiate our Component in our Application class because It only constructed once when App launches and use Scopes to provides the life and where we need that certain object.

For Dagger-2 core concepts, I suggest you this Tutorial

For Dagger-2 Android Support I suggest you this Tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM