Here's my problem:
It's first important to know that I'm writing a simulation. This is a standalone application, and is single-threaded. I have essentially two classes of objects that have different scoping requirements.
Classes that should be used as singletons throughout the entire simulation. An instance of Random, as an example.
Groups of classes that are created together, and within the group, each instance should be treated like a Singleton. For example, say
RootObject
is the top level class, and has a dependency toClassA
andClassB
, both of which have a dependency toClassD
. For any givenRootObject
, both of its dependencies (ClassA
andClassB
) should depend on the same instance ofClassD
. However, instances ofClassD
should not be shared across different instances ofRootObject
.
Hopefully that makes sense. I can think of two approaches to this. One is to mark all of the injected objects as Singletons, create the root injector, and spin off a child injector each time I need to create a new RootObject
instance. Then, the instances of RootObject
and all of its dependencies are created as Singletons, but that scoping information is thrown away the next time I go to create another RootObject
.
The second approach is to implement some type of custom scope.
The Guice documentation gives conflicting advice... On one hand, it says that you should have a single injector, and that ideally it is called once to create some top level class. On the other hand, it says to stay away from custom scopes.