Stampede10343 Stampede10343 - 7 days ago 6
Android Question

How can Dagger 2 be used to inject using multiple components into the same object

So I have an ApplicationComponent for injecting singletons into my fragments and presenters, but I'm trying to create a component to inject into the same presenter that the AppComponent does. Something along these lines.

@Component{modules = FileManagerModule.class}
public interface FileManagerComponet
{
public void inject(MyPresenter presenter);
}

@Component{modules = AppModule.class}
public interface AppComponent
{
public void inject(MyPresenter presenter);
}

@Module
public class AppModule
{
private Context appContext;
@Provides
@Singleton
public SharedPreferences preferences()
{
return appContext.sharedPreferences();
}
...
}

@Module
public class FileManagerModule
{
private Context activityContext;
@Provides
public FileManager FileManager()
{
return new FileManager(activityContext);
}
...
}

Answer

To anyone who can't figure this out, one component must provide all the dependencies to an object. So in my case, I'd have to make the FileManagerComponent be a Subcomponent and ".plus()" it with my AppComponent, or make it dependent on AppComponent and have AppComponent expose Context downstream by having a Context context(); Method that will let components that depend on it have access to a the context it has.