android - Dagger 2 依赖注入(inject)

标签 android retrofit rx-java retrofit2 dagger-2

我正在使用 dagger 2 和改造 我有两个模块

1.应用模块

2.博客模块

@Module
public class BlogModule {

   @PerActivity
    @Provides
    ApiService provideApiService(Retrofit retrofit){

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

应用组件

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

    Retrofit exposeRetrofit();
    Context exposeContext();
}

并且我在 BlogComponent 中添加了依赖

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

在我的申请中

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;
    }

当我尝试在我的基本 Actvity 中注入(inject) BlogComponent 时,我无法在 applicationComponent(getApplicationComponent()) 中添加 getApplicationComponent()

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

按照教程,他们注入(inject)如下

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

谁能帮我解决这个问题。谢谢

最佳答案

您应该能够从您的应用程序访问它

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

关于android - Dagger 2 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718884/

相关文章:

android - 如何使用改造将成功的响应主体转换为特定类型?

java - 是否可以使用 RxJava 在非主线程中调用 “onSensorChanged” 方法?

android - 如何在 LinearLayout 中添加空白区域?

android - 如何在 sqlite 中选择/删除当前时间之前 24 小时内的所有行

Android NavigationView 设置默认 fragment

android - 以编程方式打开 Android 设置

android - 从改造响应中获取 JSONArray

java - Android:无法从字符串值构造 java.sql.Timestamp 的实例

android - 如何使用 RxAndroid 压缩 Kotlin 语言中的一些 observables

java - RxJava 中的并行性 - 过滤器