【发布时间】:2023-04-01 02:38:01
【问题描述】:
我有两个组件,一个用于应用程序上下文,一个用于活动上下文,如下所示。
@Singleton
@Component(modules = {AppModule.class,})
public interface AppComponent {
@ForApplication
Context context();
//Preferences prefs(); //(Question is related to this line)
}
@PerActivity
@Component(dependencies = AppComponent.class,modules = {ActivityModule.class})
public interface ActivityComponent extends AppComponent {
void inject(ActivityA activity);
}
我有一个单例类,我想将其注入到 ActivityA 中,该类在 ActivityComponent 中声明。
@Singleton
public class Preferences {
@Inject
public Preferences(@ForApplication Context context) {
...
}
}
public class ActivityA extends AppCompatActivity {
@Inject
Preferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerActivityComponent.builder()
.appComponent(((MyApplication) getApplication()).getComponent())
.activityModule(new ActivityModule(this))
.build();
}
我在我的 Applicaiton onCreate() 和 ActivityComponent 中注入 AppComponent 在 Activity 的 onCreate 中,在这种情况下 ActivityA 就像上面一样
问题(或问题): 目前,如果我没有从我的AppComponent(第一个代码块中的注释行)公开这个单例类并且在 AppModule 中没有提供方法。我无法编译。编译错误显示我无法引用与ActivityComponent 不同的范围,我有点理解。这意味着,我无法使用 PerActivity 范围的组件访问 Singleton 范围的类。
但是,我是否必须为所有 Singleton 类提供方法并通过 AppComponent 公开它(我目前正在做和工作)?有没有更好的方法来进行 Singleton 类注入?
【问题讨论】:
标签: android dependency-injection dagger-2