In Dagger, how do @AssistedInject and @AssistedFactory build an object that needs both graph dependencies and a runtime argument, and what restrictions apply?
answer
- some arguments only known at call time
- mark the runtime parameters
- Dagger writes the factory
- inject the factory, not the type
- no scope, names for same types
basics
~20 sMark the constructor @AssistedInject and each runtime parameter @Assisted, then declare an @AssistedFactory interface whose one method takes those parameters. Dagger implements and binds the factory; you inject the factory, never the type, and the type cannot be scoped.
solid answer
~50 sAssisted injection covers objects where Dagger supplies some constructor parameters and the caller supplies others, such as an order ID from an `Intent`. I annotate the constructor with `@AssistedInject` and the caller-supplied parameters with `@Assisted`, then write an `@AssistedFactory` interface with exactly one abstract method that returns the type and takes exactly the `@Assisted` parameters; the Dagger docs ask for the same order, and the compiler pairs them by type and identifier. Dagger generates the factory implementation and binds it, so I inject `OrderDetailsLoaderFactory` and call `create(orderId)`. The rules: the `@AssistedInject` type itself cannot be injected, even with no assisted parameters; it cannot be scoped; two assisted parameters of the same type need `@Assisted("name")` on both the constructor and the factory method, because parameter names are not reliably kept; and the factory can be requested as itself or as a `Provider`, not as a `Lazy`.
code
kotlin · 30 linesimport android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import javax.inject.Inject
class OrderRepository @Inject constructor()
class OrderDetailsLoader @AssistedInject constructor(
private val repository: OrderRepository, // from the graph
@Assisted private val orderId: String, // from the caller
)
@AssistedFactory
interface OrderDetailsLoaderFactory {
fun create(orderId: String): OrderDetailsLoader
}
class OrderActivity : AppCompatActivity() {
@Inject lateinit var loaderFactory: OrderDetailsLoaderFactory
private lateinit var loader: OrderDetailsLoader
override fun onCreate(savedInstanceState: Bundle?) {
// a component's inject(this) call goes here, as in any plain-Dagger Activity
super.onCreate(savedInstanceState)
val orderId = requireNotNull(intent.getStringExtra("orderId"))
loader = loaderFactory.create(orderId)
}
}go deeper
Recall the three annotations, @AssistedInject, @Assisted and @AssistedFactory, and that you call the factory's create method with the runtime value.
Explain how Dagger generates and binds the factory, why its parameters must match the @Assisted parameters exactly, and how it differs from a hand-written factory class.
Know the compile errors: injecting the type instead of its factory, scoping it, same-type parameters without identifiers, and requesting the factory as Lazy.
Choose between assisted injection, @BindsInstance and a subcomponent by asking whether the runtime value belongs to one object or to a whole lifetime.
## The problem assisted injection solves Most objects in a Dagger graph can be built entirely from other bindings. Some cannot: an `OrderDetailsLoader` needs an `OrderRepository` from the graph **and** an `orderId` that only exists once the user taps an order. **Assisted injection** is the pattern where the DI framework supplies some constructor parameters and the caller supplies the rest at creation time, through a factory that combines them. Without framework support you write that factory by hand: a class with an `@Inject` constructor taking the graph dependencies and a `create(orderId)` method calling the real constructor. Dagger's assisted injection generates it for you. The generated factory obtains the graph-supplied parameters from the component, just as an `@Inject` constructor would, and passes your runtime arguments through unchanged, so the caller never sees the repository or any other graph dependency and the class under construction stays free of setters for late-arriving values. ## The three pieces 1. **`@AssistedInject`** on the constructor of the type to build. 2. **`@Assisted`** on each constructor parameter the caller provides. Unannotated parameters come from the graph as usual. 3. **`@AssistedFactory`** on an interface or abstract class with **exactly one abstract, non-default method** whose return type is the assisted type and whose parameters match the constructor's `@Assisted` parameters **exactly**. The Dagger docs ask for the same order; the compiler itself checks that the two sets of parameters, each identified by type plus optional identifier, are equal, and pairs them on that basis. Dagger generates an implementation of the factory and binds it in the graph. Any class can then inject the factory and call it with the runtime values. ## The rules that differ from `@Inject` An `@AssistedInject` constructor looks like an `@Inject` one, but the type behaves differently in the graph: | Rule | What happens if you break it | |---|---| | Inject the factory, not the type | `Dagger does not support injecting @AssistedInject type, ... Did you mean to inject its assisted factory type instead?` | | The type cannot be scoped | `A type with an @AssistedInject-annotated constructor cannot be scoped` | | Factory may be requested as itself or `Provider` | Requesting it as `Lazy` is an error | | Same-type assisted parameters need identifiers | Use `@Assisted("server")` and `@Assisted("client")` on both sides | - The "inject the factory" rule holds **even if the constructor has no assisted parameters**; the type is only reachable through its factory. - **No scope** follows from the purpose: each `create(...)` call builds a new object with different runtime arguments, so caching one instance would be wrong. - **Identifiers instead of parameter names**: the Dagger guide notes that parameter names are not kept in every situation, so they cannot be used to match two `Config` parameters. The string in `@Assisted("...")` does the matching. ## Where it fits among Dagger's other tools - **`@BindsInstance`** puts a runtime value into a whole component, for every binding in it. Use it for values that define the component's lifetime, such as the `Application` or a signed-in user for a session component. - **A subcomponent** gives a group of objects a shared lifetime and shared runtime inputs. - **Assisted injection** is per object: one runtime argument for one construction, no shared scope. The Dagger guide recommends its own assisted injection over older libraries such as AutoFactory and Square's AssistedInject, which predate it and need extra boilerplate to integrate. That also matters when moving to KSP: a factory generated by a processor still running under KAPT is invisible to Dagger's KSP processor, and `@AssistedInject` removes that dependency. ## Pitfalls - **Requesting the product directly.** Injecting `OrderDetailsLoader` instead of `OrderDetailsLoaderFactory` is the classic compile error. - **A mismatched parameter list.** A missing, extra or retyped parameter on the factory method fails with `The parameters in the factory method must match the @Assisted parameters in ...`, followed by the actual and expected signatures. - **Expecting scope-like sharing.** Two `create(sameId)` calls produce two objects. If several collaborators must share one, create it once and pass it around, or model the lifetime with a subcomponent. - **Using it for ViewModels in a Hilt app.** Hilt has its own integration for assisted ViewModels; that belongs to the Hilt material, not to plain Dagger.
- A Dagger @AssistedInject constructor takes two @Assisted String parameters, a user ID and an order ID: what must you add?Give each one an identifier, for example `@Assisted("userId")` and `@Assisted("orderId")`, on both the constructor parameters and the matching `@AssistedFactory` method parameters. Dagger matches assisted parameters by type plus identifier; it cannot rely on parameter names because they are not kept in every situation.
- In Dagger, when would you pick @BindsInstance on a component factory over assisted injection for a runtime value?When the value belongs to a whole lifetime rather than one object. `@BindsInstance` makes it injectable everywhere in that component, for example the signed-in account in a session component. Assisted injection suits a value used to build one object, such as the order ID for a single details loader, with a new object per `create` call.
- You can inject the @AssistedInject type directly when it has no assisted parameters.
- Annotating the assisted type @Singleton caches one instance per factory.
- Dagger matches assisted parameters by their Kotlin parameter names.
- You must write the @AssistedFactory implementation class yourself.
- Inject the factory as Lazy to delay creating it.