I have a simple situation here which I am not able to get around (since today is my second day with dagger).
I have a RepositoryManager class the intent of which is to house all repositories like(StudentRepo , TeacherRepo etc etc)
This is my RepositoryManager
public class RepositoryManager {
private static RepositoryManager INSTANCE = null;
#Inject
StudentRepo studentRepo;
#Inject
TeacherRepo teacherRepo;
private final List<Repository> repositories;
private Context context;
#Inject
public RepositoryManager(Context context) {
this.repositories = new ArrayList<>();
this.context = context;
addRepositories();
}
private void addRepositories() {
addRepository(studentRepo);
addRepository(teacherRepo);
}
I understand why my studentRepo and teacherRepo are null here. It is because I have not asked Dagger to fetch them for me . I believe I am missing some very important aspect of Dagger here in which we can explicitly fetch instances of our desired objects.
The StudentRepo btw has its own module and I can easily pull it out in an activity.
My question is just how to fetch instances in a non activity class.
my AppComponent
#Singleton
#Component(modules =
{
AndroidInjectionModule.class,
ApplicationModule.class,
ActivityBindingModule.class,
RepositoryModule.class})
public interface AppComponent extends AndroidInjector<ChallengerHuntApplication> {
RepositoryManager exposeRepositoryManager();
#Component.Builder
interface Builder {
#BindsInstance
AppComponent.Builder application(Application application);
AppComponent build();
}
}
RepositoryModule
#Module(includes = SystemRepositoryModule.class)
public class RepositoryModule {
}
Student Repository Module
#Module
public class StudentRepositoryModule {
#Singleton
#Provides
#Local
public StudentDataSource provideStudentLocalDataSource(Context context) {
return new StudentLocalDataSource(context);
}
#Singleton
#Provides
#Remote
public StudentDataSource provideStudentRemoteDataSource(Context context) {
return new StudentRemoteDataSource();
}
}
Related
How to implement Dagger for worker classes in Dagger 2.16?
public class SyncWorker extends Worker {
#Inject
ISettingRepository settingRepository;
#NonNull
#Override
public Result doWork() {
sync();
return Result.SUCCESS;
}
private void sync() {
}
}
my AppComponent
#Singleton
#Component(modules = {
AndroidSupportInjectionModule.class,
BaseModule.class,
ApiModule.class,
UserDatabaseModule.class,
SaleDatabaseModule.class,
AppModule.class,
ActivityBuilderModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
void inject(BaseApp app);
#Override
void inject(DaggerApplication application);
#Component.Builder
interface Builder {
#BindsInstance
Builder getApp(Application application);
AppComponent build();
}
}
How can I inject the settingRepository?
I was able to inject a worker with this approach.
First, create a new method inside your app component that will inject your worker class.
#Singleton
public interface AppComponent extends AndroidInjector<YourApplicationClass> {
#Component.Builder
interface Builder {
#BindsInstance
AppComponent.Builder application(Application application);
AppComponent build();
}
void inject(NotifWorker worker);
}
Inside your application, build your dagger component as usual but assign it to a variable and make it global.
public class YourApplicationClass implements HasActivityInjector {
private AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder()
.application(this)
.build();
appComponent.inject(this);
}
public AppComponent getAppComponent() {
return appComponent;
}
}
Inside your worker class, do something like this.
public class NotifWorker extends Worker {
#Inject
ToBeInjectedClass toBeInjectedClass;
public NotifWorker() {
YourApplicationClass
.getInstance()
.getAppComponent()
.inject(this)
}
}
To inject any classes in Dagger 2, you have to first provide those classes using #provides annotation in the module.
You have to first create a component containing a module which provides the desired class.
Example:-
#component(modules = {Module1.class})
public interface Component1{
void inject(SyncWorker syncWorker);
}
#Module
public class Module1{
#Provides
public ISettingRepository getSettingRepo(){
return new ISettingRepository();
}
}
Now write in your code, a constructor that is used to inject the component into your worker class.
public class SyncWorker extends Worker {
#Inject
ISettingRepository settingRepository;
public SyncWorker(){
DaggerComponent1.builder().build().inject(this);
}
#NonNull
#Override
public Result doWork() {
sync();
return Result.SUCCESS;
}
private void sync() {
}
}
Now when the constructor runs, your settingRepository instance would be initialized.
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 //scope is not necessary for parameters stored within the module
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 to access an activity or service where SoundsRepository is injected, I get a new instance, I mean, the constructor of "SoundsRepository" fires 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();
//if (LeakCanary.isInAnalyzerProcess(this)) return;
//LeakCanary.install(this);
initFirebasePersistance();
appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
appComponent.inject(this);
FrescoUtil.init(getApplicationContext());
}
public AppComponent getComponent() {
return appComponent;
}
}
In your module you have a method that provides an instance of SoundsRepository - good
In your AppComponent you are missing a:
SoundsRepository soundsRepository();
In your Global which extends Application/MultidexApplication you create your DaggerAppComponent - good
In your other activities/fragments/services just call:
Global application = (Global) getApplication();
SoundsRepository sr = application.getComponent().soundsRepository()
Android guarantees you have only one instance of your Application (Global) class for all other actvities/services (its somewhat like a singleton).
So keep your component in that application class, and whenever you need your class, call: (YourApplication) getApplication().getComponent().yourSingleInstanceSomething();
I created and tested sample code for you: https://github.com/zakrzak/StackDaggerTest
Dagger's #Singleton is just a scope, and does not guarantee returning a singular instance of a class.
In my understanding, if you:
void inject(PostView postView);
you tell Dagger to make everything you annotated with #Provided in AppModule accessible in your PostView as soon as you request it with:
#Inject
SoundsRepository soundsRepository;
then dagger just calls the #provided method which in your case returns a new SoundRepository instance:
#Singleton
#Provides
SoundsRepository provideSoundsRepository(Context ........) {
return new SoundsRepository(...);
}
which causes your problem
The dependencies provided via the application component of the app do not have a single instance.
I have the following code:
#Component (modules = AppModule.class)
public interface AppComponent {
SharedPreferences getSharedPreferences();
}
#Module
public class AppModule {
private Context appContext;
private String prefFile;
public AppModule(#NonNull Context appContext, #NonNull String prefFile) {
this.appContext = appContext;
this.prefFile = prefFile;
}
#Provides
public SharedPreferences providePreferences(){
return new AppSharedPreferences(appContext, prefFile);
}
}
#Singleton
public class AppSharedPreferences implements SharedPreferences{
public AppSharedPreferences(Context appContext, String prefFile)
//Some code
}
public class AppApplication extends Application {
private AppComponent appComponent;
private InteractorsComponent interactorsComponent;
#Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder().appModule(new AppModule(getApplicationContext(), "PREF_STORE_NAME")).build();
interactorsComponent = DaggerInteractorsComponent.builder().appComponent(appComponent).build();
}
public AppComponent getAppComponent() {
return appComponent;
}
public InteractorsComponent getInteractorsComponent() {
return interactorsComponent;
}
}
#Module
abstract class InteractorsModule {
#Singleton
#Binds
abstract InteractorA provideInteractorA(AppInteractorA interactor);
#Singleton
#Binds
abstract InteractorB provideInteractorB(AppInteractorB interactor);
}
#Singleton
#Component (modules = InteractorsModule.class, dependencies = AppComponent.class)
public interface InteractorsComponent {
InteractorA getInteractorA();
InteractorB getInteractorB();
}
#Singleton
class AppInteractorA implements InteractorA {
private AppSharedPreferences pref;
#Inject
public AppInteractor(#NonNull AppSharedPreferences pref) {
this.pref = pref;
}
//Other overridden methods
}
#Singleton
class AppInteractorB implements InteractorB {
private AppSharedPreferences pref;
#Inject
public AppInteractor(#NonNull AppSharedPreferences pref) {
this.pref = pref;
}
//Other overridden methods
}
Now, InteractorA and InteractorB to be injected in someother classes.
InteractorA and InteractorB instances themselves are singleton where ever they are injected. But of object of InteractorA and object of InteractorB, a different instance of SharedPreferences class is provided. So InteractorA has a different instance of SharedPreferences and InteractorB has a different instance of SharedPreferences.
Could someone help to make sure that both InteractorA and InteractorB have the same instance of SharedPreferences.
Thanks.
#Module
public class AppModule {
// ...
#Provides
public SharedPreferences providePreferences(){
return new AppSharedPreferences(appContext, prefFile);
}
}
Though AppSharedPreferences is annotated with #Singleton, you're calling its constructor yourself, which means that Dagger can't guarantee that there's only one SharedPreferences instance in your application. This means that you'll get a new AppSharedPreferences instance whenver you inject SharedPreferences, including through the InteractorsComponent component dependency.
You should mark providePreferences with #Singleton, or use an #Inject constructor on AppSharedPreferences so that Dagger can manage its #Singleton behavior.
after search on web for learning about this feature most topics or post was using dependency injection for Retrofit or other android useful libraries, but i have some custom class which i want to use that with DI and i can't done it, for example i have simple custom class for using SharePreference and i'm using with that as an Singleton class
in my code i can't assign correct Dagger to component on SpApplication class to use that on activities or fragments
public class SP {
private SharedPreferences preferences;
private Context context;
public SP(Context context) {
this.context = context;
}
private SharedPreferences getPrefs() {
return preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getString(SharedPrefsTypes propertyName) {
return getPrefs().getString(propertyName.toString(), "");
}
public int getInt(SharedPrefsTypes propertyName) {
return getPrefs().getInt(propertyName.toString(), 0);
}
...
public enum SharedPrefsTypes {
Login
}
}
now i'm trying to use DI for that:
AppModules class:
#Module
public class AppModules {
private Context context;
public AppModules(Context context) {
this.context = context;
}
#Provides
#Singleton
SP provideSharePreferences() {
SP sharePreference = new SP(context);
return sharePreference;
}
}
ApplicationComponent class:
#Component(modules = AppModules.class)
public interface ApplicationComponent {
void inject(ActivityMain activity);
}
SpApplication class:
public class SpApplication extends Application {
private static SpApplication self;
private ApplicationComponent component;
#Override
public void onCreate() {
super.onCreate();
self = this;
component = DaggerApplicationComponent.builder().build();
}
public static SpApplication get(Context context) {
return (SpApplication) context.getApplicationContext();
}
public static SpApplication getInstance() {
return self;
}
public ApplicationComponent getComponent() {
return component;
}
}
and my ActivityMain class:
public class ActivityMain extends AppCompatActivity {
#Inject
SP sharePreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((SpApplication) getApplication()).getComponent().inject(this);
sharePreference.setInt(SP.SharedPrefsTypes.Login, 0);
}
}
I get this error:
android.app.Application cannot be cast to com.pishguy.yendir.SpApplication
Thanks in advance
I guess you are trying to inject into ActivityMain, but since you did not provide its source, let me show you how you could inject into SpApplication. Then just copy the relevant parts into your Activity.
Few things I think you need to change.
Module:
Your AppModules class is generally OK, but I just suggest you to change the way you make use of Context - don't use it as a field, but inject it as any other service. It looks like this:
#Module
public class AppModules {
private Context context;
public AppModules(Context context) {
this.context = context;
}
#Provides // this can be non-scoped because anyway the same instance is always returned
Context provideContext() {
return this.context;
}
#Provides
#Singleton
SP provideSharePreferences(Context context) {
return new SP(context); // use method-local Context
}
}
Component:
If component injects scoped services (#Singleton is a scope), the component itself must be scoped
If you want to inject into SpApplication class, then declare it as an injection client in the component
Taking into account these two points, ApplicationComponent should look like this:
#Singleton // injects #Singleton scoped services
#Component(modules = AppModules.class)
public interface ApplicationComponent {
void inject(SpApplication application); // SpApplication is DI client (injection target)
}
Client:
I'd change few things in your SpApplication class:
The way you instantiate ApplicationComponent is incorrect
This is not a bug, but you don't really need get(Context) and getInstance() methods
In addition, since I'm showing how you inject into SpApplication, I will add the injection logic as well (which you should copy to your actual clients).
So, SpApplication (which is DI client) should look similar to this:
public class SpApplication extends Application {
#Inject SP sp; // the dependency that should be injected
private ApplicationComponent component;
#Override
public void onCreate() {
super.onCreate();
getComponent().inject(this); // this is when the actual injection takes place
}
public ApplicationComponent getComponent() {
if (component == null) {
// this is the way Dagger components should be instantiated
component = DaggerApplicationComponent.builder()
.appModules(new AppModules(this))
.build();
}
return component;
}
}
If you perform the above changes, I tend to believe that you'll be all right.
BTW, I recently completed a blog post about Dagger 2 scopes. You might want to check it if you are going to be serious about dependency injection.
I'm trying to understand and implement Dagger 2. I've already read a lot of different tutorials and official documentation. I think I understand it in general but I still can not understand some simple points (while I wrote it I've found solution for some but..):
It's possible for #Provides methods to have dependencies of their own.
When it's possible?
What I see it's possible to get "component contains a dependency cycle".
Can someone help me to understand cases when it possible and when it not possible.
Thanks.
Actually, you can use qualifiers (#Named("something") annotation) to get multiple different type of implementation for a given dependency.
#Singleton
#Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(BaseActivity baseActivity);
#Named("first")
BaseNavigator firstNavigator();
#Named("second")
BaseNavigator secondNavigator();
Context context();
//...
}
#Module
public class ApplicationModule {
private final AndroidApplication application;
public ApplicationModule(AndroidApplication application) {
this.application = application;
}
#Provides
#Singleton
#Named("first")
BaseNavigator provideFirstNavigator() {
return new SomeNavigator();
}
#Provides
#Singleton
#Named("second")
BaseNavigator provideSecondNavigator() {
return new OtherNavigator();
}
#Provides
Context provideApplicationContext() {
return this.application;
}
}
public abstract class BaseActivity extends Activity {
#Inject
#Named("second")
BaseNavigator navigator;
After very long way of many experiments I've found the answer.
I'm making this answer as cue card for myself and hope it can help other daggers jedis.
So we have dagger structure
AndroidApplication
BaseActivity
Navigator
ApplicationComponent
ApplicationModule
...
ApplicationComponent.class
#Singleton
#Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(BaseActivity baseActivity);
Navigator navigator();
Context context();
//...
}
ApplicationModule.class
#Module
public class ApplicationModule {
private final AndroidApplication application;
public ApplicationModule(AndroidApplication application) {
this.application = application;
}
#Provides
#Singleton
Navigator provideNavigator() {
return new Navigator();
}
#Provides
#Singleton
Context provideApplicationContext() {
return this.application;
}
}
Navigator.class
#Singleton
public class Navigator implements BaseNavigator {
public Navigator() {}
}
BaseActivity.class
public abstract class BaseActivity extends Activity {
#Inject
Navigator navigator;
//code here
}
This code will work and BaseActivity will get navigator as new Navigator() provided by ApplicationModule.
But if you have several implementation of BaseNavigator class you can get some certain implementation for example Navigator class without creating new instance manually.
*This construction will give you "component contains a dependency cycle"
#Provides
#Singleton
Navigator provideNavigator(Navigator navigator) {
return navigator;
}
You can do this:
ApplicationComponent.class
#Singleton
#Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(BaseActivity baseActivity);
BaseNavigator navigator(); // changed to interface type
Context context();
//...
}
ApplicationModule.class
#Module
public class ApplicationModule {
private final AndroidApplication application;
public ApplicationModule(AndroidApplication application) {
this.application = application;
}
#Provides
#Singleton
BaseNavigator provideNavigator(Navigator navigator) {
return navigator;
} // this will return interface type but with implementation you needed
#Provides
#Singleton
Context provideApplicationContext() {
return this.application;
}
}
Navigator.class
#Singleton
public class Navigator implements BaseNavigator {
#Inject // don't forget to add this annotation to the constructor
public Navigator() {}
}
BaseActivity.class
public abstract class BaseActivity extends Activity {
#Inject
BaseNavigator navigator;// changed to interface type
//code here
}
Now you did not create new instance for Navigator, Dagger did it instead of you in its generated factory.