12
Dependency Injection Using Dagger 2

Dependency Injection in Android with Dagger 2

Embed Size (px)

Citation preview

Page 1: Dependency Injection in Android with Dagger 2

Dependency Injection

Using Dagger 2

Page 2: Dependency Injection in Android with Dagger 2

What is Dependency Injection ?

It’s Famous and everybody is talking about it.

You might be using it without writing the independent examples.

Butterknife is the hint

Page 3: Dependency Injection in Android with Dagger 2

What is Dependency ?

Class Car{

getPermittedSpeed(String country){

TrafficRules rules=new Traficrules(); // Dependency

rules.getSpeed(country);

}

getAgeLimit(String country){

TrafficRules rules=new Traficrules(); // Dependency

rules.getAgeLimit(country);

}

}

Page 4: Dependency Injection in Android with Dagger 2

Class Car{

getPermittedSpeed(String country,TrafficRules rule){

rule.getSpeed(country);

}

getAgeLimit(String country, TrafficRules rule){

rule.getAgeLimit();

}

}

This is Dependency Injection

// Only god can create perfectly not you, so dont create us simply call us

Page 5: Dependency Injection in Android with Dagger 2

Class Car{

TrafficRules rules;

Car(){

rules=new TrafficRules();

}

// Dependency Resolved

getPermittedSpeed(String country){

rules.getSpeed(country);

}

getAgeLimit(String country)...

}

Wrong ! You cannot create you

should only call

Page 6: Dependency Injection in Android with Dagger 2

Class Car{

TrafficRules rules;

Car(TrafficRules rules){

this.rules= rules;

}

// Dependency Resolved

getPermittedSpeed(String country){

rules.getSpeed(country);

}

getAgeLimit(String country)...

}

Now you are a good guy!

This is correct as we are not

creating but calling

Page 7: Dependency Injection in Android with Dagger 2

Someone have to do the god’s job of Creation!

Page 8: Dependency Injection in Android with Dagger 2

Class Car{

@Inject

TrafficRules rules; // Will be done by Libraries like Dagger ?

// Dependency Resolved

getPermittedSpeed(String country){

rules.getSpeed(country);

}

}

Welcome to Dagger 2

Page 9: Dependency Injection in Android with Dagger 2

How did dagger2 know to create object ?

Secret: You will tell Dagger2, what objects it has to

create

Page 10: Dependency Injection in Android with Dagger 2

Dagger2 usage

Tell 3 Things to Dagger2

> What are the Objects Dagger 2 has to create for you

> What functions it has call for creating these Objects ?

> Where all it has to inject these pre created Objects

Page 11: Dependency Injection in Android with Dagger 2

Dagger2 usage

Tell 3 Things to Dagger2

> What are the Objects Dagger 2 has to create for you

> What functions it has call for creating these Objects ?

> Where all it has to inject these pre created Objects

@Modules

@Provides

@Component

Page 12: Dependency Injection in Android with Dagger 2

THANK YOU