Dagger 2: Difference between revisions
Jump to navigation
Jump to search
Line 41: | Line 41: | ||
return Car(frame, wheels, engine) | return Car(frame, wheels, engine) | ||
} | } | ||
} | |||
</syntaxhighlight> | |||
To share a module across modules add the include to the modules decorator | |||
<syntaxhighlight lang="kotlin"> | |||
@Module(includes = [EngineModule::class]) | |||
fun CarModule { | |||
@Provides | |||
fun provideFrame() : Frame = Frame() | |||
... | |||
@Provides | |||
fun provideCar(engine: Engine, wheels: Wheels, frame: Frame) : Car { | |||
return Car(frame, wheels, engine) | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 23:10, 19 December 2020
Introduction
Dagger is made by Google. Dagger allows you to
- Scope dependencies
- Bind single instance to life cycles
- Only need to build them once
- Generates the code at compile time
Example Without Dagger
fun buildCar: Car =
Car(SturdyFrame(),
Wheels(),
RocketEngine())
With Dagger
fun buildCar: Car =
DaggerAppComponent
.builder()
.build()
.buildCar()
Modules
Modules in Dagger are responsible for providing object we want to inject. They contain the methods which return the objects.
Modules are decorated with @module and the objects are decorated with @provides
@Module
fun CarModule {
@Provides
fun provideEngine() : Engine = Engine()
@Provides
fun provideFrame() : Frame = Frame()
@Provides
fun provideWheels() : Wheels = Wheels()
@Provides
fun provideCar(engine: Engine, wheels: Wheels, frame: Frame) : Car {
return Car(frame, wheels, engine)
}
}
To share a module across modules add the include to the modules decorator
@Module(includes = [EngineModule::class])
fun CarModule {
@Provides
fun provideFrame() : Frame = Frame()
...
@Provides
fun provideCar(engine: Engine, wheels: Wheels, frame: Frame) : Car {
return Car(frame, wheels, engine)
}
}