What is Anvil and how does it work?
mainAnvil is a Kotlin compiler plugin designed to simplify dependency injection with Dagger. It automates the process of merging Dagger modules and component interfaces into a central component.
Instead of manually adding every module to a Dagger @Component or having a component extend multiple interfaces, you use Anvil annotations to 'contribute' modules and interfaces to a specific scope. Anvil then automatically generates the Dagger code that includes these contributions.
Core Workflow:
- Define a Scope (a marker class).
- Use
@ContributesTo(Scope::class)on modules or interfaces. - Use
@MergeComponent(Scope::class)on your main component interface.
Anvil handles the boilerplate of connecting these pieces based on their shared scope.
@Module
@ContributesTo(AppScope::class)
class DaggerModule { .. }
@ContributesTo(AppScope::class)
interface ComponentInterface {
fun getSomething(): Something
fun injectActivity(activity: MyActivity)
}
// The real Dagger component.
@MergeComponent(AppScope::class)
interface AppComponent