5

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

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()还值得注意的是,当我extends DaggerInjectionFactoryMyPreferencesComponentdagger 中删除时,编译器在生成组件构建器时没有问题。

我想要做的是创建一个包含所有可注入类的接口,我想在其中使用@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;
    }
}
4

1 回答 1

0

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

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

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

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

于 2016-05-13T11:45:31.620 回答