dfdf
dfdf

Reputation: 147

Dependency injection in multiple classes?

Suppose I want to inject ObjClass obj into two different classes: Using dagger 2

class A{
   @Inject ObjClass obj
}

class B{
   @Inject ObjClass obj
}

I have component and module:

@Component @Singleton class InjectorComponent{
   void inject(A a);
   void inject(B b);
}
@Module class InjectorModule{
   @Provides
   @Singleton
   public ObjClass giveObj(){ return new ObjClass(); //This costs A LOT of CPU resources so dont want to call new ObjClass everytime}
}

In my classes A, B I have a runner method like:

void runner(){
  DaggerInjectorComponent comp = DaggerInjectorComponent.builder....
  comp.InjectorModule(new InjectorModule(...)); //IMPORTANT LINE
  comp.inject(this)
}

What I am wondering is, will this create a new Component and a new InjectorModule and also a new ObjClass each time? I want to share the same instance of ObjClass so what is the way to do it?

Does it always create a new InjectorModule?

Upvotes: 1

Views: 1725

Answers (1)

Stanislav Shamilov
Stanislav Shamilov

Reputation: 1826

Yes, in this case you will create two instances of the component and of the module; thus, you will have two instances of the ObjClass, even though you've marked it as @Singleton. The problem is that scoped dependencies are singletons only in scope of a component object. It means that creating new component instances will lead to creating new dependencies instances. Look at the example: Let's extend your void runner method:

void runner(){
  DaggerInjectorComponent comp = DaggerInjectorComponent.builder....
  comp.InjectorModule(new InjectorModule(...)); 
  comp.inject(this) //HERE YOU CREATE AND INJECT YOUR DEPENDENCY
  comp.inject(this) // HERE NOTHING WILL HAPPEN, AS DEPENDENCY IS CACHED
}

After running this code your instance is not recreated because it's marked as @Singleton, therefore it's a scoped dependency, so Dagger will know that for this instance of component it's required to initialize this object only once.

But if we recreate or component, this logic will stop working:

void runner(){
  DaggerInjectorComponent comp = DaggerInjectorComponent.builder....
  comp.InjectorModule(new InjectorModule(...)); 
  comp.inject(this) //HERE YOU CREATE AND INJECT YOUR DEPENDENCY

  comp = null
  comp = DaggerInjectorComponent.builder.... // component is recreated
  comp.InjectorModule(new InjectorModule(...)); 
  comp.inject(this) // HERE YOUR DEPENDECY IS REINITIALIZED, COMPLETELY NEW OBJECT
}

As it was said before, all singletons in dagger are tied to their component instance. If you create a new instance, it will have it's own singletons. But for you as for the client of this functionality, you'll end up with different instances.

To fix it, you mustn't recreate your component. For example, you can store it somewhere in the place which for sure won't be recreated.

I hope it helped.

Upvotes: 1

Related Questions