Search code examples
javaandroiddagger-2dagger

How to use Dagger2 library


In my application i want use Dagger2 and for this i write below codes.
My component class name is MainComponent but after rebuild project when i want use this, not found me DaggerMainComponent!
I rebuild the project several times, but it did not work again!

My Dagger dependency:

implementation 'com.google.dagger:dagger-android:2.16'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.16'

My Module class:

@Module
public class ApiServiceModule {
    private Context context;

    public ApiServiceModule(Context context) {
        this.context = context;
    }

    @Provides
    public ApisList getApisList(Retrofit retrofit) {
        return retrofit.create(ApisList.class);
    }

    @Provides
    public Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}

My Component class :

@Component(modules = ApiServiceModule.class)
public interface MainComponent {
    ApisList getApisList();
}

My mainActivity class:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }
}

How can i fix it? please help me


Solution

  • Change you dependency codes to this :

    annotationProcessor 'com.google.dagger:dagger-compiler:2.16'
    implementation 'com.google.dagger:dagger:2.16'
    

    First add this dependencies then click on Make project (ctrl+f9 shortcuts) .
    After finish rebuild project you can access to DaggerMainComponent .

    I hope help you