2模块依赖关系图

2模块依赖关系图

本文介绍了Dagger 2模块依赖关系图:绑定多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Dagger 2的新手,试图将一个(相当)复杂的应用程序移植到它.

I'm new to Dagger 2, trying to port a (quite) complex application to it.

我们对公共"库有一些依赖(与其他项目共享).这些公共"库有时依赖于其他公共"库.每个库都公开一个模块.

We have several dependencies on 'common' libraries (shared with other projects). Those 'common' libraries sometimes depend on other 'common' libraries. Each library exposes a module.

一个例子:

@Module
public class JsonModule {
    @Provides
    public Mapper provideMapper(ObjectMapper objectMapper) {
        return new DefaultMapper(objectMapper);
    }

    @Provides
    public ObjectMapper provideObjectMapper() {
        return ObjectMapperFactory.build();
    }
}

我们的HttpModule依赖于JsonModule:

Our HttpModule depends on the JsonModule:

@Module(includes = {JsonModule.class})
public class HttpModule {
    public HttpHelper provideHttpHelper(ObjectMapper objectMapper) {
        return new DefaultHttpHelper(objectMapper);
    }
}

最后,在我的应用程序中,我依赖于这两个模块:

Finally in my application, I depend on both these modules:

@Module(includes = {JsonModule.class, HttpModule.class})
public class MyAppModule {
    public Service1 provideService1(ObjectMapper objectMapper) {
        return new DefaultService1(objectMapper);
    }

    public Service2 provideService2(Mapper mappper) {
        return new DefaultService2(mappper);
    }
}

然后我有1个依赖于MyAppModule的组件:

I then have 1 component that depends on my MyAppModule:

@Component(modules = MyAppModule.class)
@Singleton
public interface MyAppComponent {
    public Service2 service2();
}

不幸的是,当我编译项目时,出现了Dagger编译器错误:

Unfortunately, when I compile the project, I get a Dagger compiler error:

[ERROR] com.company.json.Mapper is bound multiple times:
[ERROR] @Provides com.company.json.Mapper com.company.json.JsonModule.provideMapper(com.company.json.ObjectMapper)
[ERROR] @Provides com.company.json.Mapper com.company.json.JsonModule.provideMapper(com.company.json.ObjectMapper)

我做错了什么?在同一个依赖图中两次依赖一个模块是否错误?

What am I doing wrong? Is it wrong to depend on a module twice in the same dependency graph?

推荐答案

在您的 MyAppModule 中,您不应包含 JsonModule ,它是由dagger隐式包含的.当包含 HttpModule 时,dagger将自动包含 HttpModule 包含的所有模块(在您的情况下为 JsonModule ).

In your MyAppModule you shouldn't include JsonModule, it is included by dagger implicitly. When including HttpModule dagger will automatically include all modules which HttpModule includes (in your case that is JsonModule).

这篇关于Dagger 2模块依赖关系图:绑定多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:24