DI with Dagger2

18
MANAGE DI WITH DAGGER2 Philips CDP Tech Talks #15

Transcript of DI with Dagger2

MANAGE DI WITH DAGGER2Philips CDP Tech Talks #15

QUIZ

• ?

• ?

• ?

QUIZ

• What is dependencies injection?

• ?

• ?

QUIZ

• What is dependencies injection?

• Dependencies injection and dependencies inversion?

• ?

QUIZ

• What is dependencies injection?

• Dependencies injection and dependencies inversion?

• Who worked with Dagger2?

SEPARATE CONSTRUCTION AND USAGE

WRONG

public Car() {

this.motor = new Motor();

}

RIGHT

public Car(Motor motor) {

this.motor = motor;

}

DI LIBRARIES

• RoboGuice

• Dagger 1 (Classis)

• Dagger 2

DI LIBRARIES

• RoboGuice

• Dagger 1 (Classis)

• Dagger 2

ANNOTATIONS• @Module for the classes whose methods provide

dependencies

• @Provides for the methods within @Module classes

• @Inject to request a dependency

• @Component, @Subcomponent are bridge interfaces between modules and injection

EXAMPLE

• A pet project with Dagger 2

ANNOTATIONS• @Module for the classes whose methods provide

dependencies

• @Provides for the methods within @Module classes

• @Inject to request a dependency

• @Component, @Subcomponent are bridge interfaces between modules and injection

SCOPES

• Within scope Dagger will return same instance of the dependency

SCOPES

• @Singlethon

• @Scope

@NAMED@Provides @Named("cached")

OkHttpClient provideOkHttpClient(Cache cache) {

OkHttpClient client = new OkHttpClient();

client.setCache(cache);

return client;

}

@Provides @Named("non_cached")

OkHttpClient provideOkHttpClient() {

return new OkHttpClient();

}

@NAMED

@Inject @Named("cached") OkHttpClient cachedClient;

@Inject @Named("non_cached") OkHttpClient nonCachedClient;

Q&A• https://lostechies.com/derickbailey/2011/09/22/dependency-injection-is-not-the-same-as-the-dependency-

inversion-principle/

• https://en.wikipedia.org/wiki/Dependency_injection

• http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/

• http://blog.nimbledroid.com/2016/03/07/performance-of-dependency-injection-libraries.html

• http://google.github.io/dagger/

• https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2

• https://www.youtube.com/watch?v=oK_XtfXPkqw

• https://www.youtube.com/watch?v=HAzu57MrGgA

• https://www.youtube.com/watch?v=3B7F7emCc64