scott
scott

Reputation: 3202

Dagger 2 Dependency Injection

I am using dagger 2 and retrofit I have Two Modules

1.Application Module

2.BlogModule

@Module
public class BlogModule {

   @PerActivity
    @Provides
    ApiService provideApiService(Retrofit retrofit){

        return retrofit.create(ApiService.class);
    }
}

ApplicationComponent

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    Retrofit exposeRetrofit();
    Context exposeContext();
}

And I have added dependency in BlogComponent

@PerActivity
@Component(modules = BlogModule.class,dependencies = ApplicationComponent.class)
public interface BlogComponent {
    void inject(BaseActivity mainActivity);
}

And in My Application

public class BlogApplication extends Application {
    private ApplicationComponent mApplicationComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        initializeApplicationComponent();
    }


    private void initializeApplicationComponent() {

       mApplicationComponent= DaggerApplicationComponent
               .builder().applicationModule(new ApplicationModule(this))

                .build();
    }

    public ApplicationComponent getApplicationComponent(){

        return  mApplicationComponent;
    }

When I try to inject BlogComponent in My Base Actvity I cant able to add getApplicationComponent() in applicationComponent(getApplicationComponent())

DaggerBlogComponent.builder()
          .applicationComponent()
          .blogModule(new BlogModule())
          .build().inject(this);

As per tutorial they have injected as below

DaggerCakeComponent.builder()
        .applicationComponent(getApplicationComponent())
        .cakeModule(new CakeModule(this))
        .build().inject(this);

Can any one help me how I can fix this.thanks

Upvotes: 1

Views: 285

Answers (1)

pradithya aria
pradithya aria

Reputation: 687

You should be able to access it from your application

DaggerBlogComponent.builder()
          .applicationComponent(((BlogApplication)getApplication()).getApplicationComponent())
          .blogModule(new BlogModule())
          .build().inject(this);

Upvotes: 2

Related Questions