i have a problem with Singleton with the Dagger2 library for Android.
My problem is im using the #Singleton but getting two different objects =[
i Have 2 Components and 2 Modules:
DispatcherComponent which includes the DispatcherModule class that provides a Dispatcher.
the Dispatcher needs instance UserStore which is provided by StoreModule.
#Singleton
#Component(modules={AppModule.class, StoreModule.class, DispatcherModule.class})
public interface DispatcherComponent {
void inject(SomeClass someClass);
}
and the DispatcherModule.class is as follows
#Module
public class DispatcherModule {
#Provides
#Singleton
public Dispatcher provideDispatcher(UserStore store) {
Log.d("DEBUG", "userStore : " + store.toString());
return new Dispatcher(store);
}
and now the StoreComponent.class
#Singleton
#Component(modules={AppModule.class, StoreModule.class})
public interface StoreComponent {
void inject(SomeOtherClass otherClass);
}
and StoreModule.class
#Module
public class StoreModule {
#Provides
#Singleton
public UserStore provideUserStore() {
return new UserStore();
}
now when im trying to inject UserStore im getting two different objects =/
public class SomeOtherClass extends Acitivity {
#Inject UserStore mStore;
public void onCreate(Bundle savedInstance) {
StoreComponent comp = ((MyApp) getApplication).getStoreComponent();
comp.inject(this);
Log.d("DEBUG", "userStore2 :" + mStore.toString());
}
}
public class SomeClass {
#Inject Dispatcher mDispatcher;
public SomeClass (Application application) {
((MyApp) application).getDispatcherComponent().inject(this);
}
and last, this is how i create the components:
public class MyApp extends Application {
public void onCreate() {
StoreModule store = new StoreModule();
StoreComponent storeComponent = DaggerStoreComponent.builder().appModule(new AppModule(this)).storeModule(storeModule).build();
DispatcherComponent disComp = DaggerDispatcherComponent.builder().appModule(new AppModule(this)).storeModule(storeModule).dispatcherModule(new DispatcherModule()).build();
}
now, when im running the Application, i get 2 different objects ! can someone help me ? how should i fix it? i dont want to have a god component..
THanks!
Note that #Singleton dost not make the object to be singleton actually, instead, it just use the DoubleCheck class to cache which is hold by the component impl generated by dagger. Check DaggerDispatcherComponent for more detail.
For this case, you can change StoreModule like below:
#Module
public class StoreModule {
private UserStore mStore;
#Provides
#Singleton
public UserStore provideUserStore() {
return getStore();
}
private UserStore getStore() {
//lazy initialized and make sure thread safe
if (null == mStore) {
#synchronized(StoreModule.class) {
if (null == mStore) {
mStore = new UserStore();
}
}
}
return mStore;
}
}
Related
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
Hi I've read through other posts but I am not being able to fix it. Basically my issue is that I call .inject and when I want to use the field it's still null.
I have this class:
public class Application extends Game implements IApplication {
#Inject IApplication app;
#Inject IRouter router;
public Application(IPlatformCode platformCode) {
}
#Override
public void create() {
initDagger();
System.out.println(app); //NULL
System.out.println(router); //NULL
router.showPage(Page.MenuPage); //NULL EXCEPTION
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 0.5f, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
super.render();
}
#Override
public void setPage(IPage page) {
setScreen(page);
}
protected void initDagger() {
ApplicationComponent.Initializer.init(this).inject(this);
RouterComponent.Initializer.init().inject(this);
}
}
I won't show the router because I'm doing the same in app.
My Application component looks like this:
#Singleton
#Component ( modules = {ApplicationModule.class })
public interface ApplicationComponent {
void inject(IApplication application);
IApplication getApplication();
static final class Initializer {
private Initializer(){}
public static ApplicationComponent init(IApplication app) {
return DaggerApplicationComponent
.builder()
.applicationModule(new ApplicationModule(app))
.build();
}
}
}
And this is the module:
#Module
public class ApplicationModule {
private IApplication app;
public ApplicationModule(IApplication app) {
this.app = app;
}
#Provides
#Singleton
public IApplication providesApplication(){
return app;
}
}
As far as I read after calling inject(IApplication) the #Inject IApplication should be injected and have a value but right now it's null.
The generated code looks like this:
public final class DaggerApplicationComponent implements ApplicationComponent {
private Provider<IApplication> providesApplicationProvider;
private DaggerApplicationComponent(DaggerApplicationComponent.Builder builder) {
assert builder != null;
this.initialize(builder);
}
public static DaggerApplicationComponent.Builder builder() {
return new DaggerApplicationComponent.Builder();
}
private void initialize(DaggerApplicationComponent.Builder builder) {
this.providesApplicationProvider = DoubleCheck.provider(ApplicationModule_ProvidesApplicationFactory.create(builder.applicationModule));
}
public void inject(IApplication application) {
MembersInjectors.noOp().injectMembers(application);
}
public IApplication getApplication() {
return (IApplication)this.providesApplicationProvider.get();
}
public static final class Builder {
private ApplicationModule applicationModule;
private Builder() {
}
public ApplicationComponent build() {
if(this.applicationModule == null) {
throw new IllegalStateException(ApplicationModule.class.getCanonicalName() + " must be set");
} else {
return new DaggerApplicationComponent(this);
}
}
public DaggerApplicationComponent.Builder applicationModule(ApplicationModule applicationModule) {
this.applicationModule = (ApplicationModule)Preconditions.checkNotNull(applicationModule);
return this;
}
}
}
Thanks in advance.
Your inject method
void inject(IApplication application);
needs to change to
void inject(Application application);
Note the change from IApplication to just Application. You can't use interfaces for inject methods, you need to use a class.
Typically, Dagger 2 component creation is done in a class extending one of Android's Application classes. This is primarily done to ensure that these components (and the dependencies they house) are only instantiated once. (see Dagger docs for more details: https://google.github.io/dagger/users-guide)
While I haven't seen anything that says you can't wire it up differently, I haven't found an example of it, either. I'm wondering if trying to wire the components on-the-fly with the Initializer.init() calls you're making is somehow bypassing Dagger's ability to setup Components for injection correctly. Would it be possible to refactor the instantiation of the Component classes into an Application implementation instead?
The code above looks like it should work (outside of getting a new DaggerApplicationComponent instance with every init() call instead of a Singleton), I can't really explain why it doesn't.
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 have 2 modules: AndroidModule for providing Context-related objects and PhotosModule providing PhotoManager.
I want to use PhotoManager in PhotosFragment. PhotoManager depends on DbManager, which is provided by AndroidModule.
How do I connect all the dots?
The code compiles, but a NPE is thrown on this line:
mDbManager.readDatabase();
meaning that the injection of DbManager into PhotoManager did not occur, even though I set the
injects = PhotoManager.class
in AndroidModule.
Also, mDbManager is not a private field, so I don't think I have to use injection on PhotoManager's constructor; field injection should be sufficient.
What's the reason and how do I satisfy the missing dependency? I assume there may be more than one problem with my code. Note: I just started with Dagger, please keep that in mind.
Application:
public class TestApp extends Application {
private ObjectGraph mObjectGraph;
#Override
public void onCreate() {
super.onCreate();
mObjectGraph = ObjectGraph.create(getModules().toArray());
}
protected List<Object> getModules() {
return Arrays.asList(new AndroidModule(this), new PhotosModule());
}
public void inject(Object object) {
mObjectGraph.inject(object);
}
}
AndroidModule:
#Module(library = true, injects = PhotoManager.class)
public class AndroidModule {
private final TestApp mApplication;
public AndroidModule(TestApp application) {
mApplication = application;
}
#Provides
#Singleton
#ForApplication
Context provideApplicationContext() {
return mApplication;
}
#Provides
#Singleton
DbManager provideDbManager() {
return new DbManager(mApplication);
}
}
PhotosModule:
#Module(injects = PhotosFragment.class)
public class PhotosModule {
#Provides
#Singleton
PhotoManager providePhotoManager() {
return new PhotoManager();
}
}
PhotoManager:
#Singleton
public class PhotoManager {
#Inject
DbManager mDbManager;
public void doSomething() {
mDbManager.readDatabase();
}
}
PhotosFragment:
public class PhotosFragment extends Fragment {
#Inject
PhotoManager mPhotoManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((TestApp) getActivity().getApplication()).inject(this);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
///...
mPhotoManager.doSomething();
}
}
DbManager:
#Singleton
public class DbManager {
public DbManager(Context context) {
//...
}
public void readDatabase() {
//...
}
}
Here's the core of the problem: in PhotosModule, you have the provider method:
PhotoManager providePhotoManager() {
return new PhotoManager();
}
You are newing up the PhotoManager yourself, so Dagger doesn't have an opportunity to inject its dependency (the DbManager).
I think it's because you're misunderstanding the meaning of the injects property on the #Module(injects=...) annotation of the AndroidModule. You have:
#Module(library = true, injects = PhotoManager.class)
But that injects isn't needed, because you're never calling objectGraph.inject on the PhotoManager. Instead, you're only injecting the PhotoFragment, which is correct...
So one way to fix the NPE problem:
remove the injects=PhotoManager.class from AndroidModule.java:
#Module(library = true)
change PhotosModule to include AndroidModule:
#Module(injects = PhotosFragment.class, includes = AndroidModule.class)
I avoid field injection using the #Inject annotation (only use it for the top-level objects, i.e. where you do the objectgraph.inject, such as activity and fragment level), and use constructor injection instead for all the other dependencies. So I'd change PhotoManager to inject the DbManager like this:
private final DbManager mDbManager;
public PhotoManager(DbManager dbManager) {
mDbManager = dbManager;
}
I've put up the code here on GitHub.
I am playing with Dagger on Android. I created a model UserPreference, a module called PreferenceModule and another class UserPreferenceTest which is a test of the PreferenceModule. I have below 3 java files
UserPreference.java
package com.sigicn.preference;
import javax.inject.Inject;
import com.sigicn.commonmodels.Application;
public class UserPreference {
public String name, weiboAccount;
#Inject
public Application[] frequentlyUsedApps;
}
Then PreferenceModule.java
package com.sigicn.preference;
import javax.inject.Singleton;
import com.sigicn.commonmodels.Application;
import com.sigicn.utils.MiscUtils;
import dagger.Module;
import dagger.Provides;
#Module(library = true, complete = true)
public class PreferenceModule {
#Provides #Singleton UserPreference provideUserPreference() {
UserPreference userPreference = new UserPreference();
userPreference.frequentlyUsedApps = provideApplications();
return userPreference;
}
#Provides #Singleton Application[] provideApplications() {
return new Application[]{
new Application(
MiscUtils.generateUUID(), "Youtube"),
new Application(
MiscUtils.generateUUID(), "Pixi")
};
}
}
Then UserPreferenceTest.java
package com.sigicn.test.preference;
import javax.inject.Inject;
import com.sigicn.preference.PreferenceModule;
import com.sigicn.preference.UserPreference;
import dagger.Module;
import dagger.ObjectGraph;
import android.test.AndroidTestCase;
public class UserPreferenceTest extends AndroidTestCase {
#Module(injects = {UserPreference.class, UserPreferenceTest.class},
includes = PreferenceModule.class)
static class TestModule {
}
ObjectGraph objectGraph;
#Inject
UserPreference userPreference;
#Override
protected void setUp() throws Exception {
if (objectGraph == null) {
objectGraph = ObjectGraph.create(new TestModule());
}
super.setUp();
}
public void testFrequentlyUsedApps()
{
UserPreference localUserPreference = objectGraph.get(UserPreference.class);
assertNotNull(localUserPreference);
assertEquals(localUserPreference.frequentlyUsedApps.length, 2);
objectGraph.inject(this);
assertNotNull(userPreference);
assertEquals(userPreference.frequentlyUsedApps.length, 2);
assertSame(localUserPreference, userPreference);
assertSame(localUserPreference.frequentlyUsedApps, userPreference.frequentlyUsedApps);
}
}
But don't know why, that the frequentlyUsedApps of UserPreference is not injected as expected. Any idea why?
Update:
I think I have figured out the reason. It's because that I manually create UserPreference and use it in the provider. If I remove the Provider for UserPreference, and let Dagger to wire it automatically, then the field frequentlyUsedApps does get injected. So it is my fault of not understanding Dagger well.
I think you need to add some ObjectGraph#inject calls.
In each class where you have an #Inject annotation, you will also need a call to the inject method of the ObjectGraph you created.
I have had been struggling with this for a while also. I think the basic pattern is:
Annotate your fields to indicate you want to inject them
Create a module to "provide" the instances for those #Injects
Create the graph somewhere (seems like most people are doing that in
the Application class)
In the classes you want to inject stuff from your module, get an
instance of the graph and call inject(this).
I started using a singleton rather than the Application class, because at least for now I have some places were I want to inject the app itself.
So here is what I am currently doing, which seems to work pretty weill
public class Injector {
private static Injector mInjector;
private ObjectGraph mObjectGraph;
private MyApp mApp;
private Injector() {
}
public static Injector getInstance() {
if (mInjector == null) {
mInjector = new Injector();
}
return mInjector;
}
protected List<Object> getModules() {
return Arrays.asList(
new ApplicationModule(mApp),
new AndroidModule(mApp)
);
}
public void inject(Object object) {
getObjectGraph().inject(object);
}
public ObjectGraph getObjectGraph() {
return mObjectGraph;
}
public void initialize(MyApp app) {
mApp = app;
mObjectGraph = ObjectGraph.create(getModules().toArray());
System.out.println(String.format("init object graph = %s",mObjectGraph.toString()));
}
}
Then in my application class I have a constructor like this:
public MyApp() {
System.out.println("myapp construtor");
Injector.getInstance().initialize(this);
Injector.getInstance().inject(this);
}
Then when I want to inject something I do this
#Inject Bus mBus;
public GcmBroadcastReceiver() {
Injector.getInstance().inject(this);
}
I have two modules , one for production and one for test
The production one has this
#Provides #Singleton
public Bus provideBus () {
return BusProvider.getInstance();
}
and the test one has this
#Provides #Singleton
public Bus provideBus () {
return mock(Bus.class);
}