square / dagger

A fast dependency injector for Android and Java.
https://square.github.io/dagger/
Apache License 2.0
7.31k stars 3.06k forks source link

Question: can we inject one component for all activities? #539

Closed jpgpuyo closed 8 years ago

jpgpuyo commented 8 years ago

Hello, First of all, thank your for this amazing library.

I have seen many projects where the structure of components is similar to this:

Singleton scope: ApplicationComponent RepositoryModule DataModule NetworkModule

Activity scope: ActivityComponent MainActivityComponent LoginActivityComponent BrowseCategoriesComponent MapActivityComponent ActivityModule MainActivityModule LoginActivityModule BrowseCategoriesModule MapActivityModule

My question is: ¿Is considered bad practice inject ActivityComponent in all activities?

From my point of view, if you have a lot of components, you have some boiler plate code. I am working in app, using clean architecture approach, with 4 activities. I used 4 separated components and yesterday I deleted the 4 components and now I'm injecting ActivityComponent in all activities.

Now, I have something similar to this:

Singleton scope: ApplicationComponent RepositoryModule DataModule NetworkModule

Activity scope: ActivityComponent UseCasesModule

I have one single module where I have all the use cases that I can use. In every activity, I only inject use cases that I need, but in the module I provide all the use cases.

I have tested performance with https://github.com/frogermcs/AndroidDevMetrics and there is not any impact on the performance.

In my case, the DaggerActivityComponent.build() is very fast and I don't see any need in add a lot of boilerplate configuration to gain some milliseconds.

Could you give some feedback about this approach or possible problems with performance if I apply this approach to larger projects?

Thank you so much!

JakeWharton commented 8 years ago

Dagger 2 has components and this repo is for Dagger 1. But to answer your question, yes you can (and probably should) use one component. Otherwise there's a lot of boilerplate involved in setting each one up and using it as an injector.

jpgpuyo commented 8 years ago

Ok, thank you!