Dagger 2 module dependency diagram: several times

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

We have several dependencies on "shared" libraries (shared with other projects). These "shared" libraries sometimes depend on other "shared" libraries. Each library provides a module.

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 rely on both of 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); } } 

Then I 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?

+7
dagger dagger-2
source share
2 answers

In your MyAppModule you should not include JsonModule , it is implicitly enabled by a dagger. When you turn on the HttpModule dagger will automatically include all the modules that the HttpModule includes (in your case, it is JsonModule ).

+7
source share

It seems that the problem is related to our situation in the project:

  • common projects combine Groovy and Java
  • shared projects built using gradle
  • application project integrates Groovy and Java
  • application project was created using Maven and groovy -eclipse-compiler

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

+1
source share

All Articles