Junior — Middle
Can you explain what is meant by scope in the context of Dependency Injection frameworks?
sobes.tech AI
Answer from AI
The scope in the context of Dependency Injection (DI) frameworks defines the lifetime and visibility of the created dependencies (objects).
In Android, for example, when using DI (Dagger, Hilt), scope helps control how many instances are created and when:
- Singleton scope — the object is created once for the entire lifetime of the application.
- Activity scope — the object lives within a single Activity, created when the Activity is created and destroyed along with it.
- Fragment scope — the object lives within a single Fragment.
This is important for resource management and proper state separation. For example, if you have an object that should only preserve its state within one Activity, it should be marked with the appropriate scope so that a new instance is created when transitioning between Activities.
Example with Hilt:
@InstallIn(ActivityComponent::class)
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
@ActivityScope
class UserRepository @Inject constructor() {
// ...
}
Here, UserRepository will be created once for each Activity in which it is injected.