【问题标题】:Injecting Singleton class using Dagger 2.x使用 Dagger 2.x 注入 Singleton 类
【发布时间】: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


    【解决方案1】:

    还有另一种方法。将Activity 组件声明为Application subcomponent。这样,Application 组件中声明的所有内容都可以在 Activity 子组件中看到。 可以通过Acpplication组件访问Activity子组件:

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

    看看这个关于 Dagger 组件的优秀 article,尤其是在实现部分。

    【讨论】:

    • 谢谢。子组件方法更清洁。我转向子组件方法。
    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2022-09-30
    相关资源
    最近更新 更多