【问题标题】:Dagger 2 component inheritance and errorsDagger 2 组件继承和错误
【发布时间】:2015-09-09 09:51:30
【问题描述】:

我正在尝试创建以下场景:

public interface DaggerInjectionFactory {
    void inject(MyActivity myActivity);
}

@Singleton
@Component(modules = {RestModule.class})
public interface MyRestComponent extends DaggerInjectionFactory {
    RestClient provideRestClient();
}

@Singleton
@Component(modules = {PreferencesModule.class})
public interface MyPreferencesComponent extends DaggerInjectionFactory {
    SharedPreferences provideSharedPreferences();       
}

匕首编译器给了我以下错误作为响应:

error: RestClient cannot be provided without an @Provides- or @Produces-annotated method.

RestModule 包含一个@Provides @Singleton RestClient provideRestClient() 方法,还值得注意的是,当我从MyPreferencesComponent 中删除extends DaggerInjectionFactory 时,dagger 编译器在生成组件构建器时没有问题。

我要做的是创建一个包含所有可注入类的接口,我想在其中使用 @Inject 注释,并在我的“所有”组件中实现它们,所以我不必添加void inject(MyActivity myActivity); 到我的所有组件。

因为我是该框架的新手,所以我不知道正确的术语是什么,因此对于我需要搜索什么没有真正的线索。

所以我的问题是:是否可以创建这样一个结构,定义一个接口,自动将所有void inject() 方法添加到我的“所有”组件中?如果可以,怎么做?

-- 编辑-- 预期的用法类似于:

public MyActivity extends Activity {
    private RestClient restClient;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyRestComponent.Instance.build().inject(this);
        MyPreferencesComponent.Instance.build().inject(this);
    }

    @Inject
    public void setRestClient(RestClient restClient){
        this.restClient = restClient;
    }

    @Inject
    public void setSharedPreferences(SharedPreferences sharedPreferences){
        this.sharedPreferences = sharedPreferences;
    }
}

【问题讨论】:

  • 您能否提供一些(伪)代码来说明您想要实现的目标,或者您希望如何使用它?
  • @nhaarman 查看更新后的问题。

标签: android dagger-2


【解决方案1】:

您不需要为每个模块创建组件。您可以向组件添加更多模块,并在这个接口上提供所有类。

@Singleton
@Component(
    modules = {RestModule.class, PreferencesModule.class}
)
    public interface AppComponent {

    void inject(MainApplication app)
    void inject(MainActivity activity);
}

如果您要求向所有活动/片段/MainApplication 注入组件,则没有此方法。您必须指定以上哪些将获得依赖注入。

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 2018-04-20
    • 2017-08-06
    • 1970-01-01
    • 2016-07-22
    • 2020-10-07
    • 2016-11-13
    • 2018-01-16
    • 2015-08-07
    相关资源
    最近更新 更多