3
私は、アプリケーションコンテキストとアクティビティコンテキストの2つのコンポーネントを以下に示すように持っています。Dagger 2.xを使用してシングルトンクラスを挿入する
@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);
}
私はActivityComponentで宣言されたActivityAに挿入したいSingletonクラスを持っています。
@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();
}
私は
上記の問題(または質問)のように、この場合には、活動ののonCreateで私のApplicaiton
onCreate()
とActivityComponent
でActivityAをAppComponentを注入しています:私は、このシングルトンクラスを公開していない場合は、現在
AppComponent
(最初のコードブロックのコメント行)から、AppModuleにメソッドを提供していません。私はコンパイルできません。コンパイルエラーは、
ActivityComponent
とは異なるスコープへの参照を持つことができないことを示しています。つまり、PerActivityスコープのコンポーネントでシングルトンスコープのクラスにアクセスすることはできません。
しかし、私はすべてのシングルトンクラスのメソッドを提供し、AppComponent
(これは私が現在やっている)で公開する必要がありますか?シングルトンクラスの注入を行う良い方法はありますか?
ありがとうございました。サブコンポーネントのアプローチははるかにクリーンです。私はサブコンポーネントアプローチに移った。 – sat