简体   繁体   中英

How to provide a singleton in a dagger module with 2 different implementations

Imagine a dagger module that has the following two methods to provide an object.

@Provides @Singleton Cache<Settings> providesSettingsCache( Database db )
{
    return new StateCache( db, BuildConfig.VERSION_CODE );
}

@Provides @Singleton Cache<User> providesUserCache( Database db )
{
    return new StateCache( db, BuildConfig.VERSION_CODE );
}

In my example StateCache implements both the Cache<User> and the Cache<Settings> interface. Now instead of both methods returning an instance of StateCache , i'd like both methods to obviously point to the same instance. How can this be achived in Dagger? Does the module hold a reference the one instance of StateCache , and have both methods return that?

Let Dagger manage the StateCache instance.

@Provides @Singleton StateCache provideStateCache(Database db) {
  return new StateCache(db, BuildConfig.VERSION_CODE);
}

@Provides @Singleton Cache<Settings> provideSettingsCache(StateCache cache) {
  return cache;
}

@Provides @Singleton Cache<User> provideSettingsCache(StateCache cache) {
  return cache;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM