Dagger01: Setting up

1. Install the Dagger Dependencies.

def DAGGER_VERSION = "2.22"
implementation "com.google.dagger:dagger:$DAGGER_VERSION"
annotationProcessor "com.google.dagger:dagger-compiler:$DAGGER_VERSION"

implementation "com.google.dagger:dagger-android:$DAGGER_VERSION"
implementation "com.google.dagger:dagger-android-support:$DAGGER_VERSION"
annotationProcessor "com.google.dagger:dagger-android-processor:$DAGGER_VERSION"


2. Create a BaseApplication class that extends DaggerApplication

import dagger.android.AndroidInjector;
import dagger.android.support.DaggerApplication;

public class BaseApplication extends DaggerApplication {
    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        return null;
    }

}

3. Add the BaseApplication class to the Manifest file.

 <application
        android:allowBackup="true"
        android:name=".BaseApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"

3. Create a AppComponent interface where will be inject the BaseApplication using AndroidInjector

import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;

/*By extending BaseApplication as AndroidInjector we are telling AppComponent
* that we are injecting BaseApplication into the AppComponent and BaseApplication
* will be a client of the AppComponent service.*/
@Component(
        modules = {
                AndroidSupportInjectionModule.class
        }
)
public interface AppComponent extends AndroidInjector<BaseApplication> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

        AppComponent build();
    }
}


4. Not build the project once to generate the classes to be used inside the BaseApplication class.

import dagger.android.AndroidInjector;
import dagger.android.support.DaggerApplication;

public class BaseApplication extends DaggerApplication {
    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        return DaggerAppComponent.builder().application(this).build();
    }
}


Comments

Post a Comment

Popular posts from this blog

What happened to the blog ?

Why I love to be a programmer ?