Sviat Volkov
Sviat Volkov

Reputation: 133

Why Dagger Component requires @Scope annotation

When you want to provide scoped dependency, Dagger requires to annotate Component with this Scope too. What is the reason for that?

@Singleton // <- for what?
@Component(modules = [MyModule::class])
interface MyComponent {
  //...
}

@Module
interface MyModule {

    @Binds
    @Singleton
    fun provideDependency(impl: DepImpl): Dep
}

Upvotes: 0

Views: 34

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95704

Scoping in Dagger means "give this binding the same lifetime as the component that contains it", so the component itself holds onto the instance so it can provide the same instance repeatedly.

Components are also hierarchical: through subcomponents and component dependencies you can have multiple components coexisting in the same application. In a typical Android app, you might have an Application component that provides bindings for several Activity components, and and each of those Activity components provides bindings for several Fragment components.

Though Dagger could theoretically infer scopes based on which module installs it, instead of requiring you to specify which scope applies to which component, this makes it more difficult to work with classes that declare scope and @Inject annotations without an explicit Dagger binding. If you're in an Activity component that inherits bindings from an Application component (often "singleton"), and an Activity binding relies on an @ApplicationScope-annotated class with an @Inject constructor, how would Dagger know to put it in the Application component instead of the Activity component? This might also make your code harder for humans to understand—I know I'd have trouble following it.

Upvotes: 1

Related Questions