Sutty1000
Sutty1000

Reputation: 805

Dagger 2 and use of @Singleton

I have inherited a Java web service project that is using Dagger 2. Based on my so far limited understanding of Dagger I am confused as to why every single class that is injected has the singleton annotation on it in the dagger module class's. If I was creating this application without dagger they would not all be singletons, is this something specific to dagger or have the previous developers simply misused Dagger?

Upvotes: 3

Views: 4213

Answers (2)

From the section about Reusable in the user guide:

Sometimes you want to limit the number of times an @Inject-constructed class is instantiated or a @Provides method is called, but you don’t need to guarantee that the exact same instance is used during the lifetime of any particular component or subcomponent. This can be useful in environments such as Android, where allocations can be expensive.

Two main differences:

  1. @Singleton annotated class is guaranted to give always the same instance. It is needed if we keep global state in it. @Reusable do not give any guarantee.
  2. If any class requests the instance of @Singleton annotated class, double checking is performed (which is slow). In case of @Reusable, it isn't.

I'd use @Reusable scope for classes that are expensive to build (for example I'm using for Retrofit instance - but to be honest I've never made performance tests if it is worth to use this annotation at all).

On the other hand, I'm using @Singleton annotated class for the cache.

Also, if you have class which keeps encapsulated global state like this:

class StateWrapper {
  final State state;
  @Inject
  StateWrapper(State state) {
    this.state = state;
  }
}

I mean the state is de facto kept in the State class, do not annotate StateWrapper as @Singleton, always annotate the smallest part: in this case the State class. (This hint is taken from the video)

Upvotes: 1

David Medenjak
David Medenjak

Reputation: 34532

[...] every single class that is injected has the singleton annotation [...] is this something specific to dagger [...]?

Nope. @Singleton is the only scope included with Dagger by default, but you can also create custom scopes, use @Reusable which may create multiple objects but will reuse them if possible, or no scope at all.

or have the previous developers simply misused Dagger?

If possible you should just ask them. If every object is a Singleton this looks like they did not invest a lot of thought in the setup and just copy-pasted declarations, at least this would be my assumption.

Upvotes: 5

Related Questions