I have a module as follows.
@Module
public class AppModule {
private final Application app;
public AppModule(Application app) {
this.app = app;
}
@Provides
@Architecture.ApplicationContext
Context provideContext() {
return app;
}
@Provides
public Context context() {
return provideContext();
}
@Singleton
@Provides
Application provideApp() {
return app;
}
@Singleton
@Provides
SoundsRepository provideSoundsRepository(Context context, SoundsDAO soundsDAO) {
return new SoundsRepository(context, soundsDAO);
}
}
A component like this.
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(Global global);
void inject(MainActivity mainActivity);
@Architecture.ApplicationContext
Context getContext();
Application getApplication();
void inject(PostView postView);
void inject(MediaPlayerService mediaPlayerService);
}
In activity, fragment or service, I do this
@Inject
SoundsRepository soundsRepository;
@Override
protected void onCreate(...) {
((Global) getApplication()).getComponent().inject(this);
}
In SoundsRepository
@Singleton
public class SoundsRepository {
@Inject
public SoundsRepository(Context context, SoundsDAO soundsDAO) {
this.context = context;
this.soundsDAO = soundsDAO;
System.out.println(TAG + "INIT");
}
}
So now, every time I start accessing the activity or service where SoundsRepository is entered , I get a new instance, I mean, the "SoundsRepository" constructor appears again.
What am I doing wrong?
EDIT: Inject in Application Class
public class Global extends MultiDexApplication {
protected AppComponent appComponent;
private boolean calledAlready = false;
@Override
public void onCreate() {
super.onCreate();
initFirebasePersistance();
appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
appComponent.inject(this);
FrescoUtil.init(getApplicationContext());
}
public AppComponent getComponent() {
return appComponent;
}
}
source
share