Java – Using Dagger to inject a singleton?

Using Dagger to inject a singleton?… here is a solution to the problem.

Using Dagger to inject a singleton?

Is it possible to have Dagger inject singletons for you?

For now, I’ve only found a way to manually provide dependencies for singletons :

@Provides
@Singleton
public Dispatcher providesDispatcher(Context context, PPreferences preferences,
                                                       FileNameCache fileNameCache) {
    return new Dispatcher(context, preferences, fileNameCache);
}

Is this the only way to define a singleton? I prefer to do something like the following, so that Dagger injects the dependencies itself, but doing so gives me an error.

@Provides
@Singleton
public Dispatcher providesDispatcher(Dispatcher dispacher) {
    return dispacher;
}

Maybe there is another way to define singletons that allows me to inject other singletons into it?

Thanks for any help.

Edit:
I just realized that I’m doing the second method with another Singleton, but it’s a little different when I map the implementation to an interface:

@Provides
@Singleton
public Tracker providesTracker(TrackerImpl tracker) {
    return tracker;
}

TrackerImpl also injects an example of the PPreferences described above.

When I try to get it to create a Dispatcher using the second example, here’s the error I get:

error: Unknown error java.lang.IllegalStateException thrown by javac in graph validation: Dependency cycle:
0.com.example.test.Dispatcher bound by @Singleton/ProviderMethodBinding[provideKey="com.example.test.Dispatcher", memberskey="null"]
0.com.example.test.Dispatcher

Solution

Creating a Dispatcher singleton instance does not require the @Provides method (on the module). Just annotate the Dispatcher constructor with the @Inject and annotate the class with @Singleton. Whenever you inject an Dispatcher instance, Dagger uses that instance.

@Singleton
public class Dispatcher 
{
    @Inject
    public Dispatcher(..)
}

Related Problems and Solutions