I think there are various articles, so I will omit it! Roughly speaking, a method of injecting instances from outside the class to reduce coupling! If you prepare an interface and inject it into it, it will be easier to test.
Masakari is welcome! !! !! Please let me know if something is wrong or missing ...!
I would like to introduce the points that I got stuck when introducing it on Android first.
There was not enough way to specify the dependency in Gradle & I was specifying the dependency that is not necessary at this stage.
Dagger2 Official #How do I get it? I wrote only the dependencies written here, not the Java dependencies.
It was faster to look at the Github ReadMe than the official one. ..
Add the following code to gradle under app and sync.
dependencies {
...
compile 'com.google.dagger:dagger:2.14.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.14.1'
}
Now you can inject the instance externally. This is enough when you want to separate external knowledge (WebAPI, etc.) and infrastructure layer (repository). I haven't investigated when dagger.android can be used, so please let me know if you like m (_ _) m
Just create a Module, define what you want to inject into the Component, and specify @Inject
.
It supports field and constructor injection.
You can think of Module as a so-called DI container (should). The idea is to cut out the instance generation separately and manage it in one place.
//It is a good idea to add Module to suffix.
@Module
public class InfrastructureModule {
//It is a good idea to add provide to the prefix.
@singleton
@provide
public RepositoryInterafce provideXYZRepository() {
return new XYZRepository();
}
}
I write it like this.
If you specify @ Singleton
, Dagger will handle the generation as a singleton.
Component is an interface that defines where to inject any Module you create. Write like this.
//It is a good idea to add Component to suffix.
//Because it handles singleton instances@Specify Singleton. Otherwise, the build will throw an error.
@Singleton
@Component(Modules = {InfrastructureModule.class})
public class InfrastructureComponent {
//The method name is inject. It's full of manners, but if you get used to it, you can play brain muscles! w
void inject(FugaHoge fugaHoge);
void inject(FooBar fooBar);
}
@Inject
and inject it as a field or a constructor.public class FugaHoge {
//Try field injection
@Inject RepositoryInterface repository;
public FugaHoge() {
//If you run Rebuild, prefix:The component entity of Dagger is automatically generated.
//Inject in the constructor.
DaggerInfrastructureComponent.create().inject(this);
}
}
This will inject the instance into repository
.
end.
Recommended Posts