我正在尝试实现以下行为:
- 在具有不同作用域的另一个模块中使用单例作用域下的模块提供的对象。
这是我所拥有的。我根据几个答案尝试了很多更改,但仍然无法解决这个问题。
第一个模块(应绑定(bind)到应用程序的生命周期)
@Module
public class AModule {
private Context context;
public AModule(Context context) {
this.context = context;
}
@Provides
@Singleton
MySharedPreference provideMySharedPreference(SharedPreferences prefs) {
return new MySharedPreferences(prefs);
}
@Provides
@Singleton
SharedPreference provideSharedPreference() {
return context.getSharedPreferences("prefs", 0);
}
它是组件
@Component(modules = AModule.class)
@Singleton
public interface AComponent {
void inject(...);
}
第二个模块(绑定(bind)到Activity Lifecycle)
@Module
public class BModule {
@Provides
@ActivityScope
X provideX(MySharedPreferences prefs) {
return new Y(prefs);
}
}
它是组件
@Component(modules = BModule.class)
@ActivityScope
public interface BComponent {
Y Y();
}
我声明了 Activity 范围
@Scope
@Retenion(RetentionPolicy.RUNTIME)
public @interface ActivityScope{}
MySharedPreferences如下
public class MySharedPreferences {
private SharedPreferences mSharedPrefs;
@Inject
public MySharedPreferences(SharedPreferences prefs) {
mSharedPrefs = prefs;
}
// some methods
}
最后,在我的应用程序类中,我创建了 A 组件
aComponent = DaggerAComponent.builder().aModule(new AModule(getApplicationContext())).build();
编辑我尝试过的一些事情
我尝试将 includes = AModule.class
添加到 BModule 中。
我尝试将 dependency = AComponent.class
添加到 BComponent 中。
我尝试使用 ActivityScope 注释创建一个新组件。
最佳答案
如果您使用依赖组件 (dependencies =
),则需要编写一个配置方法,将 @Singleton
作用域组件的依赖关系公开到 @ ActivityScope
组件。
@Component(modules = AModule.class)
@Singleton
public interface AComponent {
void inject(...);
SharedPreferences exposeSharedPreferences();
}
提供方法将允许依赖的@ActivityScope
组件为SharedPreferences
使用@Singleton
绑定(bind):
@Component(modules = BModule.class, dependencies = AComponent.class)
@ActivityScope
public interface BComponent {
Y Y();
}
参见this question有关提供方法的更详细说明。
关于java - 具有混合范围的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45909992/