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?
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
).
It seems like the problem is related to our project's situation:
Basicly: I blame the groovy-eclipse-compiler for now. I converted the project to Gradle, and everything works now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With