Question

Is it possible to have Dagger inject singletons for you?

As things stand, I've only found a way to manually provide dependencies to 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 singletons? What I'd prefer to do is something like the following so that Dagger would inject the dependencies itself, however doing so gives me an error.

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

Perhaps there is another way to define singletons that would allow me to inject other singletons into them though?

Any help is appreciated.

EDIT: I just realized that I am doing the second approach with another Singleton, however it's a slightly different case as I'm mapping an implementation to an interface:

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

TrackerImpl is injected with an instance of the PPreferences mentioned above as well.

When I try to have it create the Dispatcher with the second example this is 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
Était-ce utile?

La solution

You do not need to have a @Provides method (on the module) for creating a Dispatcher singleton instance. Just annotate the Dispatcher constructor with @Inject and the class with @Singleton. Dagger will use that instance whenever you inject a Dispatcher instance.

@Singleton
public class Dispatcher 
{
    @Inject
    public Dispatcher(..)
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top