I've read that explicitly requesting an object instance from a DI mechanism is considered a general anti-pattern for DI/IoC. This is because, by the time the object comes into scope, it should have already been injected with all the dependencies it needs. In Guice-land, such an anti-pattern would be represented as:
Service svcImpl = (Service)injector.getInstance(Service.class);
Apparently, the one exception to this anti-pattern is the bootstrapping/dependency resolution phase, where you ask Guice for all the top-level root ("root" in the sense that all other objects flow from it) objects.
Interestingly enough, I can't find any practical, working code examples of this bootstrap process after an exhaustive online search! I would imagine it looks something like this:
public void bootstrap() {
RootObj1 root1 = (RootObj1)injector.getInstance(RootObj1.class);
RootObj2 root2 = (RootObj2)injector.getInstance(RootObj2.class);
this.root1 = root1;
this.root2 = root2;
// Since all objects flow from these two "root" dependencies, bootstrapping
// is complete. root1 and root2 contain all the dependencies the application
// needs from here on out, and the "injector" object is no longer needed.
// More importantly, injector is never used anywhere else in the code, and
// therefore the code is not in violation of this anti-pattern.
}
Is this correct, or am I way off-base here? I ask only because I can't find any working examples!!
As I write this I'm beginning to second-guess myself because this just doesn't seem feasible/practical.
This is because, in reality an application's dependency graph will be massive with many separate, disparate "dependency trees", each with their own roots. This would lead to the necessity for some kind of Bootstrapper
object, responsible for returning the roots of each of these trees so that all other objects across the codebase could request the appropriate root object to the "tree" they belong to. This is already sounding extremely convoluded.
A working code example of how bootstrapping is practiced in the real world might help bring some clarity to this for me. Thanks in advance!