使用Dagger 2.x注入Singleton类

时间:2017-01-19 12:00:38

标签: android dependency-injection dagger-2

我有两个组件,一个用于Application Context,另一个用于Activity Context,如下所示。

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

我有一个Singleton类,我想在ActivityA中注入的ActivityA中注入。

@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注入活动的onCreate中的AppComponent,在这种情况下就像上面的ActivityA一样

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

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

1 个答案:

答案 0 :(得分:2)

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

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

请查看有关Dagger组件的优秀article,尤其是实施部分。

相关问题