Using Dagger in a multi-module project

We just create a new scope and use it in our feature components.I’m going to name this scope as @FeatureScope and will put it into our core module since I want to be able to reuse it in our different feature modules.@Scope@Retentionannotation class FeatureScopeWe can finally use it in our feature components to stop breaking the rules we talked about above.@Component(modules = [Feature1Module::class], dependencies = [CoreComponent::class])@FeatureScopeinterface Feature1Component { fun inject(activity: OtherActivity)}@Component(modules = [Feature2Module::class], dependencies = [CoreComponent::class])@FeatureScopeinterface Feature2Component { fun inject(mainActivity: MainActivity)}Sharing CoreComponent across modulesOne of the most important things we wanted was to share the same instance of our ExpensiveObject across our different modules..That’s why we used the @Singleton annotation, however, so far we are still creating a new CoreComponent in every feature module, which means, we are creating a new instance of ExpensiveObject every time.The plan to avoid this is to create an interface that our application will have to implement, since the application is just an application context we can then take that context from our activities/fragments in our feature modules, check if it implements this interface and then get the core component from it..To avoid writing the same checks everywhere we will have a helper class as well.Putting all together we end up with this:The actual implementation of the interface is exactly the same as we saw at the beginning of the article..We can then just use it in our feature modules since they will have access to the application context and we will finally be sharing the same instance of CoreComponent across our modules.That was everything, you should now be able to use Dagger in a multi-module project and sharing those dependencies in a very simple an easy way.If you want to check out the code just head to: you want to see this strategy in action, you can also check the sample app I wrote for my Droidcon UK talk here:, if you have any questions please reach out on Twitter or just leave a comment.Marcos Holgado (@Orbycius) | TwitterThe latest Tweets from Marcos Holgado (@Orbycius)..Señor Android Developer for @SkySports and @SkyNews..Public speaker… More details

Leave a Reply