dependency injection and dagger2 in android paramvir singh

Post on 21-Jan-2018

161 Views

Category:

Technology

4 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Dependency

injectionAND DAGGER2 FRAMEWORK IN ANDROID

WHAT IS DEPENDENCY?

INJECTION

Push dependency from outside into the class.

• Fetch dependency

• Receive dependency

DI

Ask third party to create object, instead of create dependencies

yourself.

WHY NEED DI

Decouple classes construction from construction of your

dependency.

DEPENDENCY INVERSION PRINCIPLE

Class Dependency

Interface

Implementation

Dependen

cy

DI CONTAINER

Create and map dependency

DI LIBRARY FOR ANDROID

• Dagger 2

Dagger 2

Dagger 2 analyzes dependencies for you and generates code to

help wire them together.

WITHOUT DAGGER 2

Activities

Fragments

Views

Objects

API interface

(Retrofit)

Image Loader

(Picasso)

Shared

Preference

Network client

Image disk

cache

DAGGER USAGE

Components ObjectFind object

@Inject

Take all fields with annotation, look in the component and find the object by

type, and set the field.

DAGGER USAGE

@Inject Picasso Picasso;

@ Inject Preference preference onject

// in oncreate function

getComponent().inject(this)

Take all fields with annotation, look in the component and find the object by type, and set

the field.

ANNOTATIONS USED BY DAGGER 2

• @Module and @Provides

• @Inject

• @Components

MODULES & COMPONENTS

Activities

Fragmen

ts

Views

Objects

Network client

Shared

Preferences

Application

Network module

Storage module

Application

module

Applicati

on

compon

ent

.inject(

)

SCOPES

• @UserScope

• @Singleton

• @ActivityScope

CONSTRUCTOR INJECTION

@Provides

public StoreUserInfo

provideStorUserInfo(NetworkApi networkApi){

return new StoreUserInfo(networkApi);

}

public class MainActivity extends

AppCompatActivity {

@Inject

StoreUserInfo storeUserInfo;

@Override

protected void onCreate(Bundle

savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

((MyApplication)

getApplication()).getComponent()

.inject(this);

}

Contact:

Paramvir Singh

Paramvir.singh88@gmail.com

top related