TL;DR;
Is it acceptable for a class to depend on the ObjectGraph itself?
I need this because I need to inject dependencies on some objects that I load at runtime - at a time that is disconnected from the point at which the ObjectGraph is initialized. Here is an example that illustrates how I use ServiceLoader
framework to load concrete implementation classes of a Service at runtime, and then inject dependencies into the loaded implementation classes.
interface Plugin {
void doSomething();
}
class AwesomePlugin implements plugin {
@Inject DependencyOne dependencyOne;
@Inject DependencyTwo dependencyTwo;
void doSomething(){
// ...some implementation...
}
}
class PluginEngine{
public void start(){
ServiceLoader<Plugin> pluginLoader = ServiceLoader.load(Plugin.class);
for(Plugin plugin: pluginLoader){
//TODO: Inject plugin dependencies here
}
}
}
Doing this would require the PluginEngine
class to have access to the ObjectGraph
instance:
class PluginEngine{
private final ObjectGraph objectGraph;
public PluginEngine(ObjectGraph graph){
this.objectGraph = graph;
}
public void start(){
ServiceLoader<Plugin> pluginLoader = ServiceLoader.load(Plugin.class);
for(Plugin plugin: pluginLoader){
objectGraph.inject(plugin);
}
}
}
Is this a code smell? Is this pointing to some problem elsewhere in my code, or in the way my dependencies are set up?
While composing this question, I began to see the role of Dagger as a means of replacing arbitrary dependencies with a dependency on the ObjectGraph
itself. On Android, you use a reference to the custom Application
sub-class and use it to perform injection - which is basically just a means to get access to the ObjectGraph
itself. Is this reasoning flawed?