Does GIN support anything like child injection?

I have one application that contains sub-applications. I would like to highlight GIN injection so that each sub-application can have separate instances of the same main shared classes. I also want the injector to supply classes from some core modules to all subtasks, so that singleton instances can be shared. eg.

GIN Modules: Core - shared MetadataCache - one per sub-application UserProvider - one per sub-application 

In Guice, I can do this with createChildInjector , but I don't see the obvious equivalent in the GIN.

Is it possible to achieve something similar in the GIN?

+4
source share
2 answers

Here it is at the SOF http://code.google.com/p/google-gin/wiki/PrivateModulesDesignDoc . Hope this helps you.

+2
source

I solved this thanks to the link provided by @Abderrazakk, but since the link doesn’t work very well with the instructions, I thought that I would add an approximate solution here as well:

Private GIN modules allow you to have one level of hierarchical injection, where types registered inside a private module are visible only to other instances created in this module. Types registered inside any non-private modules are still accessible to all.

Example

Suppose you have some types of patterns for input (and input):

 public class Thing { private static int thingCount = 0; private int index; public Thing() { index = thingCount++; } public int getIndex() { return index; } } public class SharedThing extends Thing { } public class ThingOwner1 { private Thing thing; private SharedThing shared; @Inject public ThingOwner1(Thing thing, SharedThing shared) { this.thing = thing; this.shared = shared; } @Override public String toString() { return "" + this.thing.getIndex() + ":" + this.shared.getIndex(); } } public class ThingOwner2 extends ThingOwner1 { @Inject public ThingOwner2(Thing thing, SharedThing shared) { super(thing, shared); } } 

Create two such private modules (using ThingOwner2 for the second):

 public class MyPrivateModule1 extends PrivateGinModule { @Override protected void configure() { bind(Thing.class).in(Singleton.class); bind(ThingOwner1.class).in(Singleton.class); } } 

And the general module:

 public class MySharedModule extends AbstractGinModule { @Override protected void configure() { bind(SharedThing.class).in(Singleton.class); } } 

Now register two modules in our injector:

 @GinModules({MyPrivateModule1.class, MyPrivateModule2.class, MySharedModule.class}) public interface MyGinjector extends Ginjector { ThingOwner1 getOwner1(); ThingOwner2 getOwner2(); } 

Finally, we can look and see that both instances of ThingOwner1 and ThingOwner2 have the same SharedThing instance from the common module, but different Thing instances from their private registrations:

 System.out.println(injector.getOwner1().toString()); System.out.println(injector.getOwner2().toString()); 
+4
source

Source: https://habr.com/ru/post/1393120/


All Articles