Reputation: 60184
There's a class with @Inject
annotated constructor
but without a Scope
defined. What Scope
will it belong to after being injected?
// No scope
public class A {
@Inject public A() {}
}
Upvotes: 1
Views: 276
Reputation: 95654
The class/binding will be unscoped and a new instance will be created for every injection.
Dagger allows unscoped dependencies to be bound in any component, regardless of the component's scope:
- Any type with an @Inject constructor that is unscoped or has a @Scope annotation that matches one of the component’s scopes
When classes or components do have a valid scope assigned to them, they track 1:1 to the lifetime of the component in which they are declared:
Since Dagger 2 associates scoped instances in the graph with instances of component implementations, the components themselves need to declare which scope they intend to represent. For example, it wouldn’t make any sense to have a @Singleton binding and a @RequestScoped binding in the same component because those scopes have different lifecycles and thus must live in components with different lifecycles.
Put differently, if you think of scopes as "conditions in which an instance is kept and reused" where @Singleton means "always keep or reuse this instance" and @RequestScoped means "keep or reuse this instance within the same request (as long as the request-scoped component exists)", then unscoped effectively means "never keep or reuse this instance".
Upvotes: 2