Search code examples
androiddagger-2dagger

Dagger 2 How to inject one class to multiple components using Sub components?


Can any please provide example code to achieve this scenario using sub components. In MyActivity i need to fulfill dependencies from multiple components. As you can see in below code MyActivity requies injection from compA via module classA and compB via module classB.

@Component(modules = classA.class)
interface compA
{
void inject(MyActivity target);
}

@Component(modules = classB.class)
interface compB
{
void inject(MyActivity target);
}

I have been trying many different things for quite some time. I have also read official docs regarding sub components but unable to understand how to do for my scenario. Please help


Solution

  • There are many ways to do this stuff. include modules is one of that. we have to modules AndroidModules and NetworkModules.

    @Module(includes = AndroidModules.class)
    public class NetworkModules {
    //Here two module are marge ....
    }
    

    Now in My component

    @Component(modules = NetworkModules.class)
    public interface NetworkComponent {
        void inject(MyActivity activity);
    }