I read the dagger 2 documentation but still not able to find that in what condition I should use dagger2 in my application and what are the benefits of its implementation?
Asked
Active
Viewed 62 times
-2
-
It's a dependency injection framework. So it's useful whenever you need to use dependency injection. Which is whenever you need to call a method in your code that belongs to another class. Which is pretty much always? I like this article https://spring.io/blog/2011/08/26/clean-code-in-android-applications just replace Guice with Dagger – EpicPandaForce Feb 11 '17 at 18:40
-
1Possible duplicate of [Beside testing, why do we need Dagger 2?](http://stackoverflow.com/questions/41895802/beside-testing-why-do-we-need-dagger-2) – David Rawson Feb 11 '17 at 22:27
1 Answers
0
1.) to use Dagger2, you need to include it as a dependency in your project.
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
compile 'com.google.dagger:dagger:2.9'
provided 'org.glassfish:javax.annotation:10.0-b28'
Then you can use Dagger2.
2.) Whenever you have a class which is the dependency of another class.
So if you have something like this:
public int getNewRandomNumber() {
return new Random().nextInt(5000);
}
Then you have an implicit dependency on Random
and it is not mockable.
So you might want to provide this as a dependency to the method instead:
public int getNewRandomNumber(Random random) {
return random.nextInt(5000);
}
But you might be using Random
in a bunch of places, so you might want to provide it to the class itself:
public class RandomGenerator {
private final Random random;
public RandomGenerator(Random random) {
this.random = random;
}
}
After which the question surfaces: if you need an instance of RandomGenerator
, where are you getting Random
from?
Surely this is stupid:
RandomGenerator gen = new RandomGenerator(new Random());
Wouldn't it be nicer to do either this:
RandomGenerator randomGenerator = component.randomGenerator();
or
@Inject
RandomGenerator randomGenerator;
Well apparently with Dagger it's pretty easy
@Module
public class RandomModule {
@Provides
@Singleton
Random random() {
return new Random();
}
}
@Singleton
@Component(modules={RandomModule.class})
public interface SingletonComponent {
Random random();
RandomGenerator randomGenerator();
}
then
@Singleton
public class RandomGenerator {
private final Random random;
@Inject
public RandomGenerator(Random random) {
this.random = random;
}
}
or
@Singleton
public class RandomGenerator {
@Inject
Random random;
@Inject
public RandomGenerator() {
}
}
You can read more about dependency injection here

Community
- 1
- 1

EpicPandaForce
- 79,669
- 27
- 256
- 428