Guice - How to share the same Singleton instance through multiple injectors/modules

Sandro Munda picture Sandro Munda · Dec 2, 2011 · Viewed 12.8k times · Source

In guice, the @Singleton scope does not refer to the Singleton pattern.

According to the "Dependency Injection" book of "Dhanji" :

Very simply, a singleton’s context is the injector itself. The life of a singleton is tied to the life of the injector (as in figure 5.8). Therefore, only one instance of a singleton is ever created per injector. It is important to emphasize this last point, since it is possible for multiple injectors to exist in the same application. In such a scenario, each injector will hold a different instance of the singleton-scoped object.

Singleton scope

Is it possible to share the same Singleton instance through multiple modules and multiple injectors ?

Answer

sanjary picture sanjary · Dec 3, 2011

You can use Injector.createChildInjector:

// bind shared singletons here
Injector parent = Guice.createInjector(new MySharedSingletonsModule());
// create new injectors that share singletons
Injector i1 = parent.createChildInjector(new MyModule1(), new MyModule2());
Injector i2 = parent.createChildInjector(new MyModule3(), new MyModule4());
// now injectors i1 and i2 share all the bindings of parent