[英]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.