10

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.

An example:

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

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

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

I then have 1 component that depends on my MyAppModule:

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

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?

Jens Geiregat
  • 129
  • 1
  • 7
  • maybe because you include it once in HttpModule and again in MyAppModule, try removing the `includes JsonModule` in one of those places – David Medenjak Jan 11 '16 at 14:37

2 Answers2

10

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).

greenfrvr
  • 643
  • 6
  • 19
1

It seems like the problem is related to our project's situation:

  • the common projects combine Groovy and Java
  • the common projects are built using Gradle
  • the application project combines Groovy and Java
  • the application project was built using Maven and the groovy-eclipse-compiler

Basicly: I blame the groovy-eclipse-compiler for now. I converted the project to Gradle, and everything works now.

Jens Geiregat
  • 129
  • 1
  • 7