In Dagger, how do injecting T, Provider<T> and Lazy<T> differ, and how does a scope annotation change what each returns?
answer
- how many instances, and when
- Provider asks again each time
- Lazy remembers, per Lazy
- scope means one per component instance
- Lazy is not a singleton
basics
~20 sInjecting T resolves the value at injection time; Provider<T> resolves again on every get(); Lazy<T> resolves on the first get() and caches it in that one Lazy. A scope annotation makes the binding return one instance per component instance, whichever form requests it.
solid answer
~40 sWith an unscoped binding, `T` gives the injection site its own instance built at injection time, `Provider<T>` builds a fresh one on every `get()`, and `Lazy<T>` defers the build to the first `get()` and returns that same value afterwards, but only for that particular `Lazy`. A scope annotation, `@Singleton` or a custom one declared with `@Scope`, ties the binding to a component that carries the same scope: that component instance holds one instance and hands it to every request, so `Provider.get()` returns the same object each time. The scope lives exactly as long as the component instance, so I create a screen-scoped component per screen and drop it with the screen. `Provider` and `Lazy` also break dependency cycles, and `Provider` is the tool when you genuinely need several instances.
go deeper
Recall the three request forms, T, Provider<T> and Lazy<T>, and that a scope means one instance per component that carries it.
Explain the instance table for scoped and unscoped bindings, why Lazy is not a singleton, and how creating and dropping a component bounds a scope's lifetime.
Show production judgement: spot a screen object scoped too widely, a Provider retained beyond its component, and when to break a cycle with Provider instead of redesigning.
Set a team convention for custom scopes: how many lifetimes the app really has, which component owns each, and when @Reusable or no scope is the safer default.
## Three ways to request the same binding In Dagger any injection site, whether an `@Inject` constructor parameter, an `@Inject` field or a component provision method, can ask for a type in three forms. They name the same binding but change **when** and **how often** Dagger runs it: - **`T`**: Dagger resolves the value while it builds the object that asked for it, before your code runs. - **`Provider<T>`**: you receive a handle; each call to `get()` asks the binding again. - **`Lazy<T>`** (`dagger.Lazy`): you receive a handle; the first `get()` asks the binding, and every later `get()` on **that same handle** returns the remembered value. The `Lazy` contract says implementations are thread-safe and compute the value at most once. The `dagger.Lazy` javadoc demonstrates this with a module whose `@Provides` method returns an incrementing counter: direct injection prints `100 100 100` with the value computed before printing starts; `Provider` prints `100 101 102`; `Lazy` prints `100 100 100` but computes only when first asked. ## What a scope annotation adds A **scope** is an annotation that is itself annotated with `@Scope`. `@Singleton` is the standard one; you can declare your own, such as `@ActivityScope` or `@SessionScope`. Putting a scope on a binding, an `@Inject` class or a `@Provides` method, means **one instance per instance of the component that carries that scope**: - The component must be annotated with the same scope; the component implementation then keeps a reference to each scoped object and reuses it. - A module whose `@Provides` methods carry a scope may only be installed in a component with that scope. - An `@Inject` class with a scope annotation can be used by the component with that scope or any of its descendants, and Dagger stores the instance in the right one. - An **unscoped** binding has no memory: each request may get a new instance. The scope is not a global singleton. Two instances of a `@Singleton` component hold two separate `@Singleton` objects. Entering a scope means creating a component, and leaving it means dropping every reference to that component, which is why a screen-scoped component is usually created with the screen and released with it. ## How the forms combine with scopes | Request | Unscoped binding | Scoped binding, same component instance | |---|---|---| | `T` | A new instance for each injection | The component's one instance | | `Provider<T>` | A new instance on every `get()` | The same instance on every `get()` | | `Lazy<T>` | Built on the first `get()`, cached in that `Lazy` only | The component's one instance, fetched on the first `get()` | The javadoc's warning is **Lazy is not Singleton**: two objects that each inject `Lazy<Integer>` from an unscoped binding compute two different values. Use a scope to share one instance among all clients, and `Lazy` to defer an expensive build inside a single client. ## When each form earns its place 1. **`Lazy<T>`** for something expensive that a class might never use, such as a parser only needed on one code path. It also lets a constructor run without building the dependency immediately. 2. **`Provider<T>`** when you need several instances over time, for example a fresh request object per call, or a factory or builder of a subcomponent you create repeatedly. 3. **Either one** to break a dependency cycle. Dagger reports `Found a dependency cycle` when `A` needs `B` and `B` needs `A` directly; requesting one side as `Provider` or `Lazy` lets the graph be built, because the dependency is resolved later. Redesigning the two classes is often the better fix. 4. **`@Reusable`** when you want to limit how many instances get built but no particular lifetime requires a single one: the binding *may* be reused, without the guarantee a real scope gives. ## Pitfalls - **Assuming `Provider<T>` always means a new instance.** For a scoped binding it returns the shared object every time. - **Holding a `Provider` longer than its component.** In Dagger's `fastInit` mode (`-Adagger.fastInit=enabled`), every `Provider` references the whole component and its scoped instances, so a leaked `Provider` leaks the component, perhaps an `Activity` with it. - **Putting an outer scope on a screen class.** A screen class marked `@Singleton` lives as long as the application component and can outlive the screen it was built for. - **Forgetting the component scope.** A scoped binding reachable from a component that lacks that scope fails the build with an `[Dagger/IncompatiblyScopedBindings]` error.
- In Dagger, a class injects Provider<SessionCache> and SessionCache is @SessionScope in the component that built it: what do repeated get() calls return?The same `SessionCache` every time, as long as the calls go through that component instance. A scoped binding is stored once per component instance, and a `Provider` simply asks the binding again, which returns the stored object. A new instance appears only when a new session component is created.
- Why can holding a Dagger Provider in a long-lived object leak more memory with fastInit mode enabled?In the default mode a `Provider` references only the providers of its transitive dependencies. With `-Adagger.fastInit=enabled`, each `Provider` references the entire component, including every scoped instance, so keeping one alive after the component should be gone keeps the whole component alive, which may include an `Activity`.
Injecting T is being handed a coffee; a Provider is a pass you can redeem for a fresh cup each time; a Lazy is a voucher you redeem once and then keep drinking from that same cup. A scope means the café brews one pot per shop, so every pass and voucher at that shop pours from it.
- Provider<T> always returns a new instance, even for a scoped binding.
- Lazy<T> is a cheap way to make a binding a singleton.
- @Singleton gives one instance per process however many components exist.
- A scope annotation on a class works even if no component carries it.
- Lazy and Provider cannot help with a dependency cycle.