非活动 Java 类中的 Dagger 2 注入
我正在尝试将Dagger2用于DI,它对于活动/片段相关的类(其中存在onCreate生命周期事件)完全可以正常工作。现在我有一个普通的Java类,我想被注入。任何关于如何去做的想法将不胜感激。我拥有的代码如下所示:
BasicMoviesUsecaseComponent.java -
@PerActivity
@Component(dependencies = AppComponent.class, modules = BasicMoviesUsecasesModule.class)
public interface BasicMoviesUsecasesComponent {
void inject(PaymentsManager paymentsManager);
}
数据库模块.java -
@Module
public class DatabaseModule {
@Provides @Singleton
Realm provideRealmInstance(Context context) {
return Realm.getInstance(context);
}
@Provides @Singleton
DatabaseProvider provideDatabaseInstance(Realm realm) {
return new DatabaseProvider(realm);
}
@Provides @Singleton
SharedPreferences provideSharedPrefs(Context context) {
return context.getSharedPreferences(context.getPackageName()+"_prefs", Context.MODE_PRIVATE);
}
@Provides @Singleton
SharedPreferencesManager provideSharedPreferencesManager(SharedPreferences sharedPreferences) {
return new SharedPreferencesManager(sharedPreferences);
}
@Provides @Singleton
PaymentsManager providePaymentsManager(SharedPreferencesManager sharedPreferencesManager) {
return new PaymentsManager(sharedPreferencesManager);
}
}
AppComponent.java -
@Singleton
@Component(modules = {
ApplicationModule.class,
DomainModule.class,
DatabaseModule.class
})
public interface AppComponent {
Bus bus();
Realm realm();
DatabaseProvider dbProvider();
SharedPreferencesManager sharedPreferencesManager();
}
以下是我需要将共享首选项管理器注入的类,我无法执行此操作:
我的经理.java -
private class MyManager {
private SharedPreferencesManager manager;
@Inject
MyManager(SharedPreferencesManager manager){
this.manager = manager;
}
private void initializeDependencyInjector() {
BMSApplication app = BMSApplication.getInstance();
DaggerBasicMoviesUsecasesComponent.builder()
.appComponent(app.getAppComponent())
.basicMoviesUsecasesModule(new BasicMoviesUsecasesModule())
.build().inject(PaymentsManager.this);
}
}
如何调用 initializeDependencyInjector() ?