简体   繁体   English

如何在带有2种不同实现的dagger模块中提供单例

[英]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. 想象一个带有以下两种方法来提供对象的匕首module

@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. 在我的示例中, StateCache实现了Cache<User>Cache<Settings>接口。 Now instead of both methods returning an instance of StateCache , i'd like both methods to obviously point to the same instance. 现在,我不希望这两个方法都返回StateCache实例, StateCache希望这两个方法都指向同一实例。 How can this be achived in Dagger? 在Dagger中如何实现? Does the module hold a reference the one instance of StateCache , and have both methods return that? module是否持有一个StateCache实例的StateCache ,并且两个方法都返回该实例?

Let Dagger manage the StateCache instance. 让Dagger管理StateCache实例。

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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