Android 使用Dagger 2.x注入Singleton类

Android 使用Dagger 2.x注入Singleton类,android,dependency-injection,dagger-2,Android,Dependency Injection,Dagger 2,我有两个组件,一个用于应用程序上下文,另一个用于活动上下文,如下所示 @Singleton @Component(modules = {AppModule.class,}) public interface AppComponent { @ForApplication Context context(); //Preferences prefs(); //(Question is related to this line) } @PerActivity @Compo

我有两个组件,一个用于应用程序上下文,另一个用于活动上下文,如下所示

@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();

}
我正在将AppComponent注入我的应用程序中的onCreate()和onCreate of Activity中的
ActivityComponent
,在本例中,类似于上面的ActivityA

问题(或问题):当前,如果我没有从我的
AppComponent
(第一个代码块中的注释行)公开这个单例类,并且在AppModule中没有提供方法。我不能编译。编译错误表明我不能从
ActivityComponent
中引用不同的作用域,这我有点理解。这意味着,我无法使用PerActivity作用域组件访问单例作用域类


但是,我是否必须为所有Singleton类提供方法,并通过
AppComponent
(我目前正在做并且正在工作)公开它?有没有更好的方法进行单例类注入?

还有另一种方法。将
活动
组件声明为
应用程序
。这样,
应用程序
组件中声明的所有内容都可以在
活动
子组件中看到。 可以通过
acapplication
组件访问
活动
子组件:

GithubClientApplication.get(this)
            .getAppComponent()
            .provide(new ActivityModule(this))

看看这篇关于Dagger组件的精彩文章,特别是在实现部分。

谢谢。子组件方法要干净得多。我转向了子组件方法。